一、vuex状态管理
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。
state、getters、mutations、actions、module
运行流程图
1.安装
npm i vuex --save
2.引入
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
3.核心模块
(1)state
Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。
state类似于组件中的data
/src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//实例化vuex,创建仓库
const store = new Vuex.Store({
//初始状态
state:{
name:'小飞',
age:18
}
})
//把仓库暴露出去
export default store;
在页面组件中使用仓库中的数据
任意页面组件:
<p>仓库中的name为:{{ $store.state.name }}</p>
助手函数:
mapState
// 引入助手函数
import { mapState } from 'vuex'
export default {
computed:{
...mapState(['name','age'])
}
}
把仓库中的数据,作为页面组件中的计算属性去使用
(2)getters
Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
getters类似于组件中的计算属性
const store = new Vuex.Store({
...
getters:{
newage(state){
return state.age+5;
}
}
})
在页面组件中使用getters中的结果
<p>仓库中的getter为:{{ $store.getters.newage }}</p>
助手函数:
mapGetters
import { mapGetters } from 'vuex'
export default {
computed:{
...mapGetters(['newage'])
}
}
(3)mutations
直接操作state中的数据的唯一方法,内部就自行封装好的函数
mutations中的操作方法都是同步方法
const store = new Vuex.Store({
...
mutations:{
changeAge(state){
state.age++;
}
}
})
在任意页面组件中通过commit来触发定义好的函数
<button @click="$store.commit('changeAge')">改变age</button>
助手函数:
import { mapMutations } from 'vuex'
<script>
export default {
methods:{
...mapMutations(['changeAge',...])
}
}
</script>
在页面中使用
<button @click="changeAge()">改变age-同步</button>
(4)actions
actions不直接修改数据,而是通过mutations来修改数据,actions可以包含任意的异步操作
Action 类似于 mutation,不同在于:
- Action 提交的是 mutation,而不是直接变更状态。
- Action 可以包含任意异步操作。
const store = new Vuex.Store({
...
actions:{
CHANGEAGE(store,info){
// setTimeout(function(){
// },3000)
store.commit('changeAge',info)
}
}
})
在任意页面组件中使用actions
<button @click="$store.dispatch('CHANGEAGE')">改变age-异步</button>
<button @click="$store.dispatch('CHANGEAGE',2)">改变age-异步传参</button>
助手函数:
import { mapActIons } from 'vuex'
<script>
export default {
methods:{
...mapActions(['CHANGAGE',...])
}
}
</script>
在页面中使用
<button @click="CHANGAGE()">改变age-异步</button>
(5)modules
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块。
示例代码:
在仓库中增加子模块
const store = new Vuex.Store({
...
modules:{
shop:{//shop是模块名称,可以自行设置
namespaced:true,//启用命名空间
state:{
name:'shop name'
},
mutations:{
changeName(state,data){
state.name = data;
}
}
}
}
})
在页面中调用子模块中的状态和方法
<p>仓库中shop模块的name为:{{ $store.state.shop.name }}</p>
<button @click="$store.commit('shop/changeName','王一')">改变name-shop模块</button>