vuex基本结构
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
num: 2
},
mutations: {
changeNum(state,val) {
state.num = val
}
},
actions: {
todo({ commit }, val) {
commit('changeNum', val)
}
},
getters: {
getNum(state) {
return state.num
}
},
modules: {} // 此处先不不用modules,另外的文章详解
});
state:存放数据
mutations:直接对数据进行的操作
actions:提供行为,从而触发操作(即mutations),无法直接对数据进行操作
getters:返回vuex中的数据
使用简介
在main.js中:
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store"; // 引入
Vue.config.productionTip = false;
// vuex自带了类似于Vue.prototype.$store = store方式,这种方式在页面中使用就是this.$store
// 与map的使用会有其他不同在vuex详解的文章说明
new Vue({
router,
store, // 使用
render: h => h(App)
}).$mount("#app");
在页面中,如 home.vue:
import mapActions,mapGetters from "vuex"
// mapActions遍历vuex中actions里的方法,mapGetters则是getters
methods: {
...mapActions(['todo']) // 这里就是在vuex中定义的actions
},
computed: {
...mapGetters(['getNum'])
}
更详细的使用参见:https://blog.csdn.net/HockJerry/article/details/114066175