router,
//vuex必须加入
store,
components: { App },
template: ‘’
})
复制代码
3.vuex的使用
老大有{{showData}}
复制代码
老二有{{$store.state.count}}
复制代码
4.流程介绍
如图当没有使用vuex时流程为: view->actions->state->view
使用了vuex后流程为vuecomponent->(dispatch)actions->(commit)mutations->(mutate)state->(render)->vuecomponent
5.mutation
状态更改,更改 Vuex 的 store 中的状态的唯一方法是提交mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的事件类型 (type)和一个回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数。
// The Vue build version to load with the import
command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from ‘vue’
import App from ‘./App’
import router from ‘./router’
//vuex使用
import Vuex from ‘vuex’
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
//全局变量
count: 31231
},
//更改状态方法
mutations: {
//state为上面的state
addData(state) {
// 变更状态
state.count++
}
}
})
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: ‘#app’,
router,
//vuex必须加入
store,
components: { App },
template: ‘’
})
复制代码
然后执行更改
老大有{{showData}}
修改按钮
复制代码
6.getters过滤
可以限制mutation 比如小于0就不能减少了
// The Vue build version to load with the import
command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from ‘vue’
import App from ‘./App’
import router from ‘./router’
//vuex使用
import Vuex from ‘vuex’
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
//全局变量
count: 0
},
//更改状态方法
mutations: {
//state为上面的state
addData(state) {
// 变更状态
state.count++
}
},
//过滤
getters: {
getState(state) {
if (state.count >= 5) {
return 5
} else {
return state.count
}
}
}
})
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: ‘#app’,
router,
//vuex必须加入
store,
components: { App },
template: ‘’
})
复制代码
调用时
老二有{{$store.getters.getState}}
复制代码
7.Action–异步处理
Action 类似于 mutation,不同在于:
Action 提交的是 mutation,而不是直接变更状态。 Action 可以包含任意异步操作。 mutation只能同步处理 main.js。示例如下:
// The Vue build version to load with the import
command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from ‘vue’
import App from ‘./App’
import router from ‘./router’
//vuex使用
import Vuex from ‘vuex’
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
//全局变量
count: 0
},
//更改状态方法
mutations: {
//state为上面的state
addData(state) {
// 变更状态
state.count++
}
},
//过滤
getters: {
getState(state) {
if (state.count >= 5) {
return 5
} else {
return state.count
}
}
},
actions: {
//action触发的mutations方法 优势是异步处理
addData(context) {
//模拟异步
setTimeout(() => {
context.commit(‘addData’)
}, 1000)
}
}
})
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: ‘#app’,
router,
//vuex必须加入
store,
components: { App },
template: ‘’
})
复制代码
在发送时 应该调用action。
老大有{{showData}}
修改按钮