Vuex是vue.js应用开发的状态管理模式,vuex的核心是store(仓库),这个Store中包含着大部分的状态。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
Vuex适用
vuex适用于大型单页面
Vuex的使用
-
安装vuex
cnpm i vuex
-
在store中的index.js中注册实例并且通过export default来导出
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
})
- 在main.js中的实例中全局引用
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
State数据源
vuex中的数据源,我们需要用到的数据都被保存在这里,可以通过this.$store.state来获取到
在store中的index.js中设置需要全局访问的store,把它放在创建的实例中
const state = {
count:1
}
export default new Vuex.Store({
state,
})
在app.vue页面中通过this.$store.state.count来获取这个count的值
created() {
console.log(this.$store.state.count)
}
Getters
不过一般情况下我们需要state的值不是最初始的那个值,是需要获取操作之后的值。可以通过官方提供的getters来进行监听state值得改变,与computers相似
const getter = {
getCount(){
return state.count
}
}
export default new Vuex.Store({
state,
getter
})
通过this.$store.getters.getCount获取改变后的值
Mutations
单单有getters并不能改变数据,还需要结合mutations来,在mutations中存放改变state的方法,具体的操作是在mutations中的方法传入state或者额外的参数,利用vue的双向数据驱动来改变值,将定义好的mutations放入到实例store中
const mutations = {
changeCount(state,num){
state.count += num
}
}
export default new Vuex.Store({
state,
getter,
mutations
})
可以通过this.$store.commit(‘changeCount’, 3)来改变count的值
Actions
actions是类似于mutations的,但有两点不同
- Action 提交的是mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
count:1
}
const getters = {
getCount(state){
return state.count
}
}
const mutations = {
changeCount(state,num){
state.count += num
console.log(state.count)
}
}
const actions = {
getChange(context,num){
context.commit('changeCount',num)
console.log(state) //5
}
}
export default new Vuex.Store({
state,
getters,
mutations,
actions
})
改变值得状态时不直接去操作mutations而是在actions中去操作mutations通过dispatch来调用this.$store.dispatch(‘getChange’, 4)改变值得状态
mapState
当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性
computed: mapState({
count() {
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
return this.$store.state.count
}
})