vuex 主要是用来解决大型系统的数据存储和同步问题。vuex的核心是store, store中的状态是响应式的,当state发生改变,页面使用的值会发生改变,页面会重新渲染。举个例子:
import { createApp } from 'vue'
import { createStore } from 'vuex'
// 创建一个新的 store 实例
const store = createStore({
state () {
return {
count: 0
}
},
mutations: {
increment(state, payload) {
state.count = payload.amount;
}
},
// action可以用来调用mutation方法
actions: {
increment(context) { // context可以解构为{dispatch, commit, state}
context.commit('increment', {amount: 1});
// 调用incre
dispatch('incre');
},
incre() {
...
}
}
})
const app = createApp({ /* 根组件 */ })
// 将 store 实例作为插件安装
app.use(store)
在程序中可以通过this.$store获取store实例并修改状态值:
import { mapMutations } from 'vuex'
methods: {
increment() {
this.$store.commit('increment', {amount: 1});
console.log(this.$store.state.count);
}
// or
...mapMutations[
'increment', // 程序中使用this.increment({amount:1})
]
// or
...mapActions[
add: 'increment', // 映射actions increment方法,程序中使用this.add({amount:1})
]
dispatchFun() {
this.$store.dispatch('increment', {amount: 1})
}
}
当状态发生改变的使用,在computed方法中获取最新状态:
import { mapState } from 'vuex'
// vuex将$store注入到根组件中,子组件均可使用
const Counter = {
template: `<div>{{ count }}</div>`,
computed:{
...mapstate({
count: state => state.count,
// 名称相同时
'count',
})
}
}
actions方法可以时异步方法,当为异步方法时举例:
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}
// 在程序中使用.then
this.$store.commit('actionA').then(res=>{})
// 使用 async await
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
this.$store.commit('actionA')