1、安装vuex(npm install vuex -S)
2、建立一个js文件(如:store.js,一般放入src目录下)
import Vue from ‘vue’
import Vuex from ‘vuex’
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count:0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
}
})
3、在main.js中引入store.js
import store from ‘./store’;
new Vue({
router,
store,
render: h => h(App)
}).$mount(’#app’)
4、组件里使用vuex 的值
computed: {
count() {
return this.$store.state.count;//加粗部分为取值
}
},
5、触发里面函数改变值
methods:{
click_first(){
//this.$store.state.count+=1;
this.$store.commit('increment');
}
}