store/index.js 中创建 store
import { createStore } from 'vuex'
import other from './other'
export default createStore({
// 这里的state就相当于组件中的data,就是专门用于保存共享数据的
state: {
count: 0,
todos: [],
},
// 用于定义计算属性
getters: {
doneTodos: (state) => {
return state.todos.filter(todo => todo.done)
},
// 接受其他 getter 作为第二个参数
doneTodosCount (state, getters) {
return getters.doneTodos.length
},
// 通过让 getter 返回一个函数,来实现给 getter 传参
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
},
// 用于保存修改共享数据的方法
// 注意点:在执行mutations中定义的方法的时候,系统会自动给这些方法传递一个state参数
// state中就保存了共享的数据
// mutations必须是同步函数
mutations: {
increment (state, num) {
state.count += num
}
},
// 用于保存修改共享数据的方法
// 注意点:接受一个与 store 实例具有相同方法和属性的 context 对象
// context中就包含state,commit,dispatch...
// actions可以包含任意异步操作
actions: {
incrementAsync ({ state, commit }, payload) {
setTimeout(() => {
commit('increment', payload.num)
}, 1000)
}
},
// 解决action异步的方法
actionA ({ state }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(state.count)
resolve()
}, 1000)
}),
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
console.log()
})
}
},
modules: {
other,
}
})
子模块:store/other.js
import other from './other'
export default {
state: {
otherCount: 1
},
// 模块内部的 getter,根节点状态会作为第三个参数暴露出来
getters: {
sumWithRootCount (state, getters, rootState) {
return state.otherCount + rootState.count
}
},
mutations: {},
// 模块内部的 action,局部状态通过 context.state 暴露出来,根节点状态则为 context.rootState
actions: {
fun1({state,rootState}){
console.log( state.otherCount, rootState.count )
}
}
}
main.js 中注册 store
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.use(store)
app.mount('#app')
vue 组件中使用 store
import { mapState, mapGetters } from 'vuex'
export default {
// ...
computed: {
...mapGetters([
'doneTodosCount',
// ...
]),
...mapState({
count: state => state.count,
})
},
mounted:{
console.log(this.$store.state.count)
console.log(this.$store.getters.doneTodosCount)
this.$store.commit('increment', 10)
this.$store.dispatch('incrementAsync', {num: 10})
this.$store.dispatch('actionA').then(() => {})
},
}