1、安装:
cnpm i vuex -S
2、新建vuex状态管理文件夹于src/ 下
image.png
3、store/index.js 文件内容
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
// 变量
state: {
count: 1
},
// 方法
mutations: {
add(state, num) {
state.count += num;
},
reduce(state, num) {
state.count -= num;
}
}
})
export default store;
- 在项目入口文件 main.js 中引入vuex
import Vue from 'vue'
import Layout from './layout'
import router from './router'
Vue.config.productionTip = false
// 引入vuex
import store from './store'
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { Layout },
template: '<Layout/>'
})
4、调用属性和方法
this.$store.state.count
this.$store.commit("add", 2);