在一些小项目中其实能够不用vuex的,可是在一些大型项目中,vuex必然是必杀技,能够使你方便使用,方便跟踪视图的状态。
一、编写store对象javascript
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')
// 应用初始状态
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
}
})
// 建立 store 实例
return store
})复制代码
二、app中的vuex
须要在启动的时候也就是vue-cli脚手架中的app.vue中把store注入大根目录,一次注入终身受用。如图
vue
store
,并注入到
vue
的根组件。若是想要实现模块化状态控制,则参考如下3。
define([], function() {
var modelA = {
state:{
name: 3
},
// 定义所需的 mutations
mutations:{
INCREMENT: function(state) {
state.name++
},
DECREMENT: function(state) {
state.name--
}
}
}
return modelA;
})复制代码
四、子组件中使用java
vuex: {
getters: {
count: state => state.count//变量必须放这里,这里也能够是函数,当过滤器用
},
actions: {
increment:function(dispatch){
dispatch.dispatch('INCREMENT')//触发修改变量
},
decrement:function(dispatch) {
dispatch.dispatch('DECREMENT')
}
}
},
created: function() {
},
`复制代码
同时也能够这样用vuex
this.$store.dispatch('DECREMENT');//触发方法
this.$store.commit('DECREMENT');//触发方法vuex2,在actions里面触发的方法
this.$store.state.count='ssss';//修改变量的值
this.$store.state.test.name='ssss';//修改模块变量的值复制代码
五、测试实例
一、google浏览器的控制台vue-cli
2.测试模块化变量浏览器