1.在package.json中增加vuex
"vuex": "^3.6.2"
2.运行npm install
3.在src目录下新建store目录,在store目录中创建文件store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
export default store;
4.在需要的页面引入store,并使用
//路径
import store from './store/store'
store.commit('increment');
alert(store.state.count);
也可以在根实例中引入上述store. 修改main.js
1)
import store from './store/store'
new Vue({
render: h => h(App),
router,
store
}).$mount('#app')
3)之后就可以全局使用store了
alert(this.$store.state.count);