Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预|测的方式发生变化。
vuex 需要 学习 state , getter , action , mutation , module;
官方文档
https://vuex.vuejs.org/zh/guide/
复制 vue-route 项目
安装 vuex
npm install --save vuex
main.js 配置使用vuex
import Vue from 'vue';
import App from './app.vue';
import VueRouter from 'vue-router';
import Vuex from 'vuex'
Vue . use(VueRouter) ;
Vue.use(Vuex);
const store = new Vuex.Store({
// vuex 配置
state : {
count : 0
}
});
// 省略其它配置
new Vue({
el: '#app',
router: router,
// 使用vuex
store: store,
render: h => {
return h(App)
}
});
仓库 store 包含 数据的状态和操作过程;如果数据发送变化,对应的组件也会发生变化;
index.vue 内容如下,在任何组件中都可以通过 this.$store.state.count
获取 count;
<template>
<div>
<h1>首页</h1>
<router-link to="/about">跳转到 about</router-link>
<p> {{count}} </p>
</div>
</template>
<script>
export default {
computed : {
count() {
return this.$store.state.count;
}
}
}
</script>
使用命令 npm run dev 页面就显示 默认数值 0;
main.js 使用 mutations 对值进行计算
/ vuex常量配置
const store = new Vuex.Store({
// vuex 配置
// 存储值
state : {
count : 0
},
// 计算值
mutations: {
increment(state){
state.count++;
},
decrease(state) {
state.count--;
}
}
});
在组件中通过 this.$store.commit 调用 mutations 方法
index.vue, 实现 加 1 , 减 1 计算;
<template>
<div>
<h1>首页</h1>
<router-link to="/about">跳转到 about</router-link>
<button @click="handleIncrease">+1</button>
<button @click="handledecrease">-1</button>
<p> {{count}} </p>
</div>
</template>
<script>
export default {
computed : {
count() {
return this.$store.state.count;
}
},
methods: {
handleIncrease() {
this.$store.commit("increment");
},
handledecrease(){
this.$store.commit("decrease");
}
}
}
</script>
指定增量计算示例,也可以进行传参不对n进行赋默认值;
increment(state, n=2){
state.count += n;
},
Action:用于提交Mutation的动作,从而更改Vuex中的State;
const store = new Vuex.Store({
state: {
items: []
},
mutations: {
add (state, item) {
state.items.push(item)
}
},
actions: {
add (context) {
context.commit('add')
}
}
})
在组件中使用 this.$store. dispatch触发 actions;
使用getter对数据进行统一处理,避免每个组件都需要计算一次;即代替computed 计算属性抽出公共方法。
main.js
const store = new Vuex.Store({
// vuex 配置
// 存储值
state : {
list : [1,3,5,7,9,11,13]
},
getters: {
filterNum: state => {
return state.list.filter(item => item < 10);
}
}
});
index.vue
<template>
<div>
<h1>首页</h1>
<p> {{list}} </p>
</div>
</template>
<script>
export default {
computed : {
list() {
return this.$store.getters.filterNum;
}
}
</script>
当 state , getter, action, 非常多时就需要使用 module
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态