Vuex的模块化使用
目的: 让代码更好的维护,让更多数据分类更加明确。比如有个user的数据,多个组件使用不冲突
1. 修改js
js
import Vue from 'vue'
import Vuex from "vuex"
import countOptions from "@/store/count";
import personOptions from "@/store/person";
Vue.use(Vuex)
// 创建store
export default new Vuex.Store({
modules: {
countOptions,
person: personOptions
}
})
js
export default {
namespaced: true, // 开启命名空间
actions: {
jiaSumOdd(context, num) {
if (context.state.sum % 2 == 1) {
context.commit('JIA_SUM_ODD', num)
}
},
addSumWait(context, num) {
setTimeout(() =>{
context.commit('JIA_SUM_WAIT', num)
}, 500)
}
},
mutations: {
'JIA': function (state, num){
state.sum += num
},
'JIAN': function (state, num){
state.sum -= num
},
JIA_SUM_ODD(state, num) {
state.sum += num
},
JIA_SUM_WAIT(state, num) {
state.sum += num
}
},
state: {
sum: 0
},
getters: {
bigSum(state){
return state.sum * 10
}
}
}
js
import axios from 'axios'
export default {
namespaced: true, // 开启命名空间
actions: {
addPerson(context) {
axios.get('https://fakerapi.it/api/v1/persons?_locale=zh_CN&_quantity=1')
.then(response => {
let person = response.data.data[0]
let newId = 0
if (context.state.personList.length) {
newId = context.state.personList[0].id + 1
}
person.id = newId
console.log(person)
context.commit('ADD_PERSON', person)
}, error => {
console.log(error)
})
}
},
mutations: {
'ADD_PERSON': function (state, person) {
state.personList.unshift(person)
}
},
state: {
personList: []
},
getters: {
country(state) {
return state.personList[0].address.city
}
}
}