template-project/store/modules/moduleA.js

88 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// 购物车模块
export default {
state:{//存放状态
token:'token已生成',
userInfo:{},
count:0,
publicColor:'',
todos: [{
id: 1,
text: '我是内容一',
done: true
},
{
id: 2,
text: '我是内容二',
done: false
}
],
obj:{
a:'吃鸡腿',
b:'吃自助餐'
}
},
// Vuex中store数据改变的唯一方法就是mutations 不适合异步方法
mutations: {
add(state) {
state.count = 7;
},
add2(state, payload) {
state.count = payload.amount;
},
// 单个属性处理方法
setToken(state,str) {
state.token = str;
},
// 对象处理方法
updateUserInfo(state, payload) {
// 变更状态
state.userInfo = payload.userInfo;
},
// 新增字段方法
newProp(state,payload) {
state.obj = { ...state.obj, c: payload.c };
}
},
// 可以执行任意的同步和异步操作
actions:{
addCountAction ({commit}) {
commit('add')
},
addCountAction2 (context , payload) {
context.commit('add2', payload)
},
// 异步方法
addCountAction3 (context , payload) {
setTimeout(function () {
context.commit('add2', payload)
}, 2000)
},
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
},
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
},
// Vuex 允许我们在 store 中定义“getter”可以认为是 store 的计算属性),对 state 的加工,是派生出来的数据。 可以在多组件中共享 getter 函数,这样做还可以提高运行效率。
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
},
doneTodosCount: (state, getters) => {
//state :可以访问数据
//getters访问其他函数等同于 store.getters
return getters.doneTodos.length
},
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
}