Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
Vuex
它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化.Vuex 也集成到 Vue 的官方调试工具 devtools extension (opens new window),提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能
使用
在安装项目的时候直接配置
目录中
|-src
|-store
index.js vuex的配置文件
加入你的项目已经建好了突然想用vuex(不推荐 配置信息过多)
单独在项目中下载
npm i vuex -D
yarn add vuex -D
Vuex 依赖 Promise (opens new window)。如果你支持的浏览器并没有实现 Promise (比如 IE),那么你可以使用一个 polyfill 的库,例如 es6-promise (opens new window)
npm install es6-promise --save # npm
yarn add es6-promise # Yarn
为了在 Vue 组件中访问 this.$store property,你需要为 Vue 实例提供创建好的 store
在main.js 中 添加store
new Vue({
el: ‘#app’,
store
})
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: { // 存储公用的数据
n:1
},
getters:{ // 类似 computed 计算
m:function(state){
return state.n+1
}
},
mutations: { // 更改数据 唯一推荐的更改方式
addN:function(state){
setTimeout(() => {
state.n++;
}, 1);
}
},
actions: { // 类似 mutations 可以做异步操作
asyncAddN(context){
setTimeout(() => {
context.commit('addN');
}, 1);
}
},
modules: { // 模块快的 将 vuex进行模块化
}
})
this.$store.state.n //获取状态对象
this.$store.commit('函数名称') // 触发状态变更
this.$store.dispatch('函数名称)
this.$store.state.a.xxx
官方推荐的简写方法 mapState, mapMutations, mapActions, mapGetters
用法一样 同时使用多个的简写
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})