在store目录下新建一个index.js:
// index.js
export const state = () => ({
str: '你好'
})
export const getters = {
}
export const mutations = {
}
export const actions = {
}
模块的写法,再在store目录下新建user.js:
// user.js
export const state = () => ({
nickname: '你好'
})
export const getters = {
}
export const mutations = {
}
export const actions = {
}
再在pages下面的index.vue里面去取:
// index.vue
<template>
<div>
{{ nickname }}
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'IndexPage',
computed: {
...mapState(['nickname'])
}
}
</script>
我们要去调用,所以不等你直接写。
// index.vue
<template>
<div>
{{ nickname }}
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: 'IndexPage',
computed: {
...mapState({
nickname: state => state.user.nickname
})
}
}
</script>
这样的话就可以又出来,就是这么一个情况。如果commit的话,或者直接在mutation里面去写。
// user.js
export const state = () => ({
nickname: '你好'
})
export const getters = {
}
export const mutations = {
changeName(state) {
state.nickname = '李四'
}
}
export const actions = {
}
接着就用:
// index.vue
<template>
<div>
{{ nickname }}
<button @click="changeName">按钮</button>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
name: 'IndexPage',
computed: {
...mapState({
nickname: state => state.user.nickname
})
},
methods: {
...mapMutations({
changeName: 'user/changeName' // 就是说是user模块下的changeName
})
}
}
</script>
当然,commit也是行得通的。
// index.vue
<template>
<div>
{{ nickname }}
<button @click="btn">按钮</button>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex'
export default {
name: 'IndexPage',
computed: {
...mapState({
nickname: state => state.user.nickname
})
},
methods: {
...mapMutations({
changeName: 'user/changeName' // 就是说是user模块下的changeName
}),
btn() {
this.changeName(); // 是可以的
this.$store.commit('user/changeName') // 可以传参,也可以不传。
}
}
}
</script>
接下来写一下vuecli中的写法,
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import user from './modules/user'
const store = () => new Vuex.Store({
modules: {
user
}
})
export default store;
这样子的话,对于重构来说就很友好。