Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化
如果在初始化项目时,选择了安装 vuex,那么无需进行这一步的安装。
安装 npm insatll vuex --save
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
// 存储你想要的值(一个仓库的作用)
state: {
count: 0,
str: "abcd234",
dataList: []
},
// 对数据做进一步的处理
getters: {
strLen: state => state.str.length
},
// mutations,用来改变 state 中的值。当然只能是同步操作
mutations: {
increment(state, payload) {
// 改变state中的数据
state.count = payload.number;
},
changeData(state, payload) {
state.dataList = payload
}
},
// actions 可以是异步操作
actions: {
getSong({ commit }, id) {
fetch('https://api.github.com/repos/vmg/redcarpet/issues?state=closed').then(res => res.json().then(res => {
commit('changeData', res)
}))
}
}
})
我们使用 console.log
将 vuex
打印出来
{
Store: ƒ Store(options)
createLogger: ƒ createLogger(ref)
createNamespacedHelpers: ƒ (namespace)
install: ƒ install(_Vue)
mapActions: ƒ (namespace, map)
mapGetters: ƒ (namespace, map)
mapMutations: ƒ (namespace, map)
mapState: ƒ (namespace, map)
}
Vuex
实际上是一个对象,包含 Store这一构造函数,mapActions
、mapGetters
、mapMutations
、mapState
这几个辅助方法
获取 state
中的值
<p>{{ this.$store.state.count }}</p>
如果状态过多,这样的写法也是很麻烦的,Vuex 中提供了 mapState。
import { mapState } from 'vuex'
export default {
computed: {
...mapState(['count'])
},
}
这样页面当中就可以直接使用 count 变量了。
<h1>{{ count }}</h1>
获取 Getter
中的值
<h2>Getters: {{ this.$store.getters.strLen }}</h2>
或者使用 Vuex
中提供了 mapGetters
computed: {
...mapGetters(['strLen'])
},
修改 state
中的值
对于在 store
中编写的 increment
方法。
handleClick() {
this.$store.commit('increment', {
number: 10
})
}
Vuex
中提供了 mapMutations
export default {
methods: {
...mapMutations(['increment']),
handleClick() {
this.increment({ number: 10})
}
},
}
实际开发中,会有很多处理异步的操作,最典型的莫过于获取服务端数据。Vuex 允许在 action 中进行异步操作。
action 中需要 commit 一个 mutation。
getData() {
this.$store.dispatch('getSong')
}
Vuex
中提供了 mapActions
methods: {
...mapActions(['getSong']),
getData() {
this.getSong()
}
},
对于一个仓库而言,如何获取值与设置值才是最重要的,剩下的都是花里胡哨的招式。
总结:
获取值使用 this.$store.state
或者是 mapState
。如果希望对获取的值进行处理,可以使用 getter
,获取 getter 使用 this.$store.getters
或者是 mapGetters
。
值的修改,对于同步操作,可以在 mutations
中编写,使用该方法可以通过 this.$store.commit
或者是 mapMutations
。对于异步操作,可以在 actions 中编写,使用该方法可以通过 this.$store.dispatch
或者是 mapActions
。