vue2(对应的vuex为3,版本不一致会出问题,会出现挂载不上去的问题):
//store.js
import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)
let user = {
namespaced: true, //一定要开始命名空间。
state: { userid: 1234 },
actions: {
changeId(context,val){
context.commit('setUserId',val)
}
},
mutations: {
setUserId(state, val) {
state.userid = val;
}
},
getters: {
getUserId(state){
return state.userid
}
}
}
// 初始化
const store = new Vuex.Store({
state:{
count:0
},
getters:{
getCount(state){
return state.count
}
}
mutations:{
increment (state, value) {
state.count = state.count + value
},
decrement (state, value) {
state.count = state.count - value
}
}
actions:{ //一般用于异步操作
async queryData (context, value) {
// 调用接口获取数据
const res = await axios.get(...,value)
//最后还是调用mutations的方法
context.commit('increment', res.data.count)
}
}
modules:{
user
}
})
export default store
//main.js
import store from '@/store'
new Vue({
// 把store对象挂载到vue实例对象中
store,
render: h => h(App),
}).$mount('#app')
使用:
//获取state参数,写在computed中
import {mapState} from 'vuex'
computed: {
//写法一:
count () {
return this.$store.state.count
}
//写法二:
...mapState(['count','user']),
}
//获取getters,写在computed中
import {mapGetters} from 'vuex'
//写法一
methods:{
getCount() {
return this.$store.getters.getCount
},
getUserId() {
return this.$store.getters['user/getUserId']//获取不同模块
}
}
//写法二:
computed: {
...mapGetters(['count']),
...mapGetters('user',[getUserId]),//获取不同模块
}
//获取mutations,写在methods中
import {mapMutations} from 'vuex'
methods:{
//写法一:
...mapMutations(['increment']),
...mapMutations('user',['setUserId']),//获取不同模块
//写法2
getCount() {
return this.$store.commit('increment',1)},
}
getUserId() {
return this.$store.commit['user/setUserId','洒水']//获取不同模块
}
}
//获取actions,写在methods中
import {mapActions} from 'vuex'
methods:{
//写法一:
...mapActions(["queryData"]),
...mapActions('user',['changeId']),//获取不同模块
//写法2
query() {
this.$store.dispatch('queryData',999)
},
changeId() {
this.$store.dispatch('changeId','改名')
},
}