state:存储初始化数据,取值 :this.$store.state.msg
getters:对state的数据二次处理,类似filter的作用 取值:this.$store.getters.newmsg
mutations: 对数据进行计算的方法全部写里面,类似computed,触发使用this.$store.commit(‘mutationNmae’)触发Mutations方法改变state的值 —-同步
actions:处理mutations中已经写好的方法,触发方式是this.$store.dispatch(actionName) —-异步
modules:模块化vuex
state getters mutations 使用例子:
1. main.js文件
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import VueCompositionApi from '@vue/composition-api'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
Vue.use(VueCompositionApi)
Vue.config.productionTip = false;
new Vue({
router,
store,
render: (h) => h(App),
}).$mount("#app");
2. store/index.js
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
msg: "hello",
},
getters:{
newmsg: state => state.msg + " world"
},
mutations: {
//set_msg 是函数名,传参第一个参数是固定是state,第二个参数,是set_msg接受的参数放在value this.$store.commit('set_msg',"hi")
set_msg(state,value){
//修改msg的值为传参过的值
state.msg = value
}
},
actions: {},
modules: {},
});
3. vue文件使用this.$store 进行调用并修改msg的值
// vuex 取值测试
console.log("初始化state的msg的值是:"+this.$store.state.msg)
console.log("初始化getters的newmsg的值是:"+this.$store.getters.newmsg)
this.$store.commit('set_msg',"hi")
console.log("修改后state的msg的值是:"+this.$store.state.msg)
4. 查看
actions 例子
同步:
<div id="app">
<p>{{ count }}</p>
<p>
<button @click="increment">+</button>
<button @click="decrement">-</button>
</p>
</div>
actions里面使用
actions: {
actions_increment (context) {
context.commit(‘increment’)
}
}
actions_increment 函数名
context 参数里面包含state mutations dispatch getters rootGetters rootState
context.commit(‘increment’) 使用commit方法,参数increment是mutations里面的函数名
// make sure to call Vue.use(Vuex) if using a module system
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
},
decrement (state) {
state.count--
}
},
actions: {
actions_increment (context) {
context.commit('increment')
}
}
})
new Vue({
el: '#app',
computed: {
count () {
return store.state.count
}
},
methods: {
increment () {
//this.$store.commit('actions_increment') 调用
store.dispatch('actions_increment')
},
decrement () {
store.commit('decrement')
}
}
})