1钧忽、編寫store對象
define([], function() {
var Vue = require('vue')
var Vuex = require('src/libs/vuex/vuex.js')
Vue.use(Vuex)
var modelA= require('src/libs/vuex/modelA.js')
// 應用初始狀態(tài)
var state = {
count: 2
}
// 定義所需的 mutations
var mutations = {
INCREMENT: function(state) {
state.count++
},
DECREMENT: function(state) {
state.count--
}
}
//這一塊可以引入模塊對象
var store = new Vuex.Store({
state: state,
mutations: mutations,
modules: {
test: modelA
}
})
// 創(chuàng)建 store 實例
return store
})
2逼肯、app中的vuex
vuex
用require引入
store
汉矿,并注入到vue
的根組件3备禀、modelA書寫方式
define([], function() {
var modelA = {
state:{
name: 3
},
// 定義所需的 mutations
mutations:{
INCREMENT: function(state) {
state.name++
},
DECREMENT: function(state) {
state.name--
}
}
}
return modelA;
})
4、子組件中使用
vuex: {
getters: {
count: state => state.count//變量必須放這里曲尸,這里也可以是函數(shù),當過濾器用
},
actions: {
increment:function(dispatch){
dispatch.dispatch('INCREMENT')//觸發(fā)修改變量
},
decrement:function(dispatch)
{
dispatch.dispatch('DECREMENT')
}
}
},
created: function() {
},
同時也可以這樣用
this.$store.dispatch('DECREMENT');//觸發(fā)方法
this.$store.commit('DECREMENT');//觸發(fā)方法vuex2,在actions里面觸發(fā)的方法
this.$store.state.count='ssss';//修改變量的值
this.$store.state.test.name='ssss';//修改模塊變量的值
5纽乱、測試實例
1昆箕、google瀏覽器的控制臺
測試非模塊化變量
2.測試模塊化變量
模塊化測試
- 可以看出,dispatch會觸發(fā)方法名相同的函數(shù)
- 相對來說薯嗤,vuex比window定義的數(shù)據(jù)更有模塊性和追蹤性。有問題可以隨時交流镜粤。