直接上步驟
一、右擊src
,新建store
目錄培漏,再右擊store
目錄,新建store.js
胡本,里面代碼如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
//狀態(tài)數(shù)據(jù),要設(shè)置全局訪問的state對象
const state = {
hello: null,
hello2: null
};
const actions = {
dosomething(context, payload) {
context.commit('dosomething', payload);
},
doanything(context, payload) {
context.commit('doanything', payload);
}
};
const mutations = {
dosomething(state, payload) {
this.state.hello = payload
},
doanything(state, payload) {
this.state.hello2 = payload
}
};
const store = new Vuex.Store({
state,
actions,
mutations
});
export default store;
簡單描述一下牌柄,從組件中提交方法名以及參數(shù)到store.js
中的action
,action
再提交到mutations
打瘪,之后再mutations
里面對state
里面的參數(shù)進(jìn)行操作
二友鼻、繼續(xù)配置,需要讓所有的組件都能夠接觸到store.js
闺骚,打開main.js
進(jìn)行配置
//首先引入store從相應(yīng)的目錄
import store from './store/store.js'
//在Vue實(shí)例里面添加store
new Vue({
store,
render: h => h(App),
}).$mount('#app')
三彩扔、組件怎么提交呢?
//在組件中
this.$store.dispatch('dosomething', this.$data.value)
this.$store.dispatch('dosomething', this.$data.value2)
四僻爽、別的組件可以監(jiān)聽store
中屬性狀態(tài)的改變虫碉,相應(yīng)的作出反應(yīng)
//在別的組建中,先寫一個計(jì)算屬性胸梆,將狀態(tài)中的屬性值返回回來
computed: {
getvalue() {
return this.$store.state.hello;
}敦捧,
getvalue2() {
return this.$store.state.hello2;
}
}须板,
//再用watch觀察數(shù)值是否發(fā)生了變化,如果變化了立馬作出一些措施
watch: {
getvalue(val, oldVal) {
console.log(val);//打印新的數(shù)值
console.log(voldVal);//打印舊的數(shù)值
},
getvalue2(val, oldVal) {
console.log(val);//打印新的數(shù)值
console.log(voldVal);//打印舊的數(shù)值兢卵,Ps:用來調(diào)用方法或者傳遞數(shù)值
}
}