首先下载依赖
npm install vuex@next --save
yarn add vuex@next --save
创建一个store文件
store的代码
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
export default new Vuex.Store({
state: {
age:1
//要想修改这里面的值,唯一的方法是提交mutations
//使用store变量的方法
this.$store.state.age
},
getters: {
//类似computed
},
mutations: {
//类似methods,但不能放异步方法
test(state){
state.1++
}
//页面中的使用方法
this.$store.commit('test')
},
actions: {
//类似methods,可实现异步方法(实际调用了mutations中的方法来实现)
asyncAwl(context){
setTimeout(()=>{
context.commit('test')
},2000)
}
//使用方法
this.$store.dispatch("asyncAwl")
}
})
在main.js中引入创建的store文件
import store from './store'
//在Vue根组件中挂载store
new Vue({
el: '#app',
store,
components: { App },
template: '<App/>'
})
如果项目比较大的话建议把仓库模块化,详见从 Vuex 0.6.x 迁移到 1.0 — Vue.js
如果是vue3项目的话建议去看ssr 详见状态管理 | Vue.js