【前端开发】Uniapp:状态管理Vuex
Vuex是一个专为 Vue.js 应用程序开发的状态管理模式,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化
- 状态自管理应用包含:
- state,驱动应用的数据源
- view,以声明方式将 state 映射到视图
- actions,响应在 view 上的用户输入导致的状态变化
- Vuex与全局变量区别:
vuex /// 全局变量
不能直接改变store里面的变量,由统一的方法修改数据 /// 可以任意修改
每个组件可以根据自己vuex的变量名引用不受影响 /// 全局变量可能操作命名污染
解决了多组件之间通信的问题 /// 跨页面数据共享
适用于多模块、业务关系复杂的中大型项目 /// 适用于demo或者小型项目 - Vuex规则:
- 应用层级的状态应该集中到单个 store 对象中
- 提交 mutation 是更改状态的唯一方法,并且这个过程是同步的
- 异步逻辑都应该封装到 action 里面
- Vuex核心:
- 每个Vuex应用的核心是store(仓库),它包含着你的应用中大部分的state(状态),状态管理有5个核心(
state、getter、mutation、action、module
)
State
- 单一状态树,定义应用状态的默认初始值,页面显示所需的数据从该对象中进行读取
- Vuex 使用单一状态树,用一个对象就包含了全部的应用层级状态。它便作为一个“唯一数据源”而存在。这也意味着,每个应用将仅仅包含一个 store 实例
- 单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照
- 不可直接对 state 进行更改,需要通过 Mutation 方法来更改
- 获取state:
- 通过属性访问,需要在根节点注入
store
<script>
import store from '@/store/index.js';//需要引入store
export default {
data() {
return {}
},
computed: {
username() {
return store.state.username
}
}
}
</script>
- 在组件中使用,通过
this.$store
访问到state
里的数据
<script>
export default {
data() {
return {}
},
computed: {
username() {
return this.$store.state.username
}
}
}
</script>
- 通过mapstate辅助函数获取
mapstate
当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。 为了解决这个问题,我们可以使用 mapState 辅助函数 帮助我们生成计算属性,让你少按几次键
<script>
import { mapState } from 'vuex'//引入mapState
export default {
data() {
return {}
},
computed: mapState({
// 从state中拿到数据 箭头函数可使代码更简练
username: state => state.username,
age: state => state.age,
})
}
</script>
当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组
computed: mapState([
'username',//映射 this.username 为 store.state.username
'age',
])
mapState 函数返回的是一个对象。使用对象展开运算符将多个对象合并为一个,以使我们可以将最终对象传给 computed 属性。极大地简化写法
computed: {
//使用对象展开运算符将此对象混入到外部对象中
...mapState({
username: state => state.username,
age: state => state.age,
})
},
为了能够使用 this 获取组件自己的data数据,必须使用常规函数
computed: {
...mapState({
username: function (state) {
return this.firstName + ' ' + state.username
},
age: state => state.age,
})
},
getter
- 可以认为是 store 的计算属性,对 state 的加工,是派生出来的数据
- 就像 computed 计算属性一样,getter 返回的值会根据它的依赖被缓存起来,且只有当它的依赖值发生改变才会被重新计算
- 可以在多组件中共享 getter 函数,这样做还可以提高运行效率
在 store 上注册 getter,getter 方法接受以下参数:
state, 如果在模块中定义则为模块的局部状态
getters, 等同于 store.getters
const store = new Vuex.Store({
state: {
todos: [{
id: 1,
text: '我是内容一',
done: true
},
{
id: 2,
text: '我是内容二',
done: false
}
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
},
doneTodosCount: (state, getters) => {
//state :可以访问数据
//getters:访问其他函数,等同于 store.getters
return getters.doneTodos.length
},
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
})
- 获取getters
- 通过属性访问,getter会暴露为
store.getters
对象
注意,getter 在通过属性访问时是作为 Vue 的响应式系统的一部分缓存其中的
<script>
import store from '@/store/index.js'//需要引入store
export default {
computed: {
todos() {
return store.getters.doneTodos
}
}
}
</script>
- 通过
this.$store
访问
export default {
computed: {
todos() {
return this.$store.getters.doneTodos
}
}
}
- 通过方法访问
你也可以通过让 getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用,注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果
<script>
export default {
computed: {
todos() {
return this.$store.getters.getTodoById(2)
}
}
}
</script>
- 通过mapGetters辅助函数访问
mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性
<script>
import {mapGetters} from 'vuex' //引入mapGetters
export default {
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodos',
'doneTodosCount',
// ...
])
}
}
</script>
如果你想将一个 getter 属性另取一个名字,使用对象形式
<script>
import {mapGetters} from 'vuex' //引入mapGetters
export default {
computed: {
...mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
doneCount: 'doneTodosCount'
})
}
}
</script>
Mutation(Vuex中唯一改变store数据的方法)
- mutations 里面装着改变数据的方法集合,处理数据逻辑的方法全部放在 mutations 里,使数据和视图分离
- Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数
你不能直接调用一个 mutation handler。这个选项更像是事件注册:“当触发一个类型为 add 的 mutation 时,调用此函数”,要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
add(state) {
// 变更状态
state.count += 2
}
}
})
<script>
import store from '@/store/index.js'
export default {
computed: {
count() {
return this.$store.state.count
}
},
methods: {
addCount() {
store.commit('add')
}
}
}
</script>
- 传入参数
- 你可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload):
- 还是以累加器的例子来实现 mutation 函数的传参,来动态定义累加的数量
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
add(state, n) {
state.count += n
}
}
})
<script>
import store from '@/store/index.js'
export default {
computed: {
count() {
return this.$store.state.count
}
},
methods: {
addCount() {
store.commit('add', 5)//每次累加 5
}
}
}
</script>
在 mutation 传参(载荷)可以也可以传递一个对象
mutations: {
add(state, payload) {
state.count += payload.amount
}
}
methods: {
addCount () {//把载荷和type分开提交
store.commit('add', { amount: 10 })
}
}
- 提交方式:
- 对象风格的提交方式
methods: {
addCount() {//整个对象都作为载荷传给 mutation 函数
store.commit({
type: 'add',
amount: 6
})
}
}
- 通过 mapMutations 辅助函数提交
使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
add(state) {
// 变更状态
state.count += 2
}
}
})
<script>
import { mapMutations } from 'vuex'//引入mapMutations
export default {
computed: {
count() {
return this.$store.state.count
}
},
methods: {
...mapMutations(['add'])//对象展开运算符直接拿到add
}
}
</script>
- 遵守规则
- 既然 Vuex 的 store 中的状态是响应式的,那么当我们变更状态时,监视状态的 Vue 组件也会自动更新。这也意味着 Vuex 中的 mutation 也需要与使用 Vue 一样遵守一些注意事项:
- 最好提前在你的 store 中初始化好所有所需属性
- 当需要在对象上添加新属性时,你应该使用 Vue.set(obj, ‘newProp’, 123), 或者以新对象替换老对象。例如,利用对象展开运算符我们可以这样写:
state.obj = { ...state.obj, newProp: 123 }
- Mutation 必须是同步函数
Action
- action 类似于 mutation ,不同在于:
- action 提交的是 mutation,通过 mutation 来改变 state ,而不是直接变更状态
- action 可以包含任意异步操作
action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters
const store = new Vuex.Store({
state: {
count: 1
},
mutations:{
add(state) {
// 变更状态
state.count += 2
}
},
actions:{
addCountAction (context) {
context.commit('add')
}
}
})
实践中,我们会经常用到 ES2015 的参数解构来简化代码(特别是我们需要调用 commit 很多次的时候)
actions: {
//参数解构
addCountAction ({commit}) {
commit('add')
}
}
- 分发Action
action
通过store.dispatch
方法触发
<script>
import store from '@/store/index.js';
export default {
computed: {
count() {
return this.$store.state.count
}
},
methods: {
add () {
store.dispatch('addCountAction')
}
}
}
</script>
actions 支持以载荷形式分发
const store = new Vuex.Store({
state: {
count: 1
},
mutations:{
add(state, payload) {
state.count += payload.amount
}
},
actions:{
addCountAction (context , payload) {
context.commit('add',payload)
}
}
})
<script>
import store from '@/store/index.js';
export default {
computed: {
count() {
return this.$store.state.count
}
},
methods: {
add () {
// 以载荷形式分发
store.dispatch('addCountAction', {amount: 10})
}
}
}
</script>
actions 支持以对象形式分发
methods: {
add () {
// 以对象形式分发
store.dispatch({
type: 'addCountAction',
amount: 5
})
}
}
action 可以执行任意的同步和异步操作
const store = new Vuex.Store({
state: {
count: 1
},
mutations:{
add(state) {
// 变更状态
state.count += 2
}
},
actions:{
addCountAction (context) {
//在执行累加的时候,会等待两秒才执行
setTimeout(function () {
context.commit('add')
}, 2000)
}
}
})
调用异步 API 和分发多重 mutation
actions: {
checkout ({ commit, state }, products) {
// 把当前购物车的物品备份起来
const savedCartItems = [...state.cart.added]
// 发出结账请求,然后乐观地清空购物车
commit(types.CHECKOUT_REQUEST)
// 购物 API 接受一个成功回调和一个失败回调
shop.buyProducts(
products,
// 成功操作
() => commit(types.CHECKOUT_SUCCESS),
// 失败操作
() => commit(types.CHECKOUT_FAILURE, savedCartItems)
)
}
}
- 通过mapActions辅助函数分发
- 使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store )
也支持传入参数(载荷),支持传递一个对象
<script>
import { mapActions } from 'vuex'
export default {
computed: {
count() {
return this.$store.state.count
}
},
methods: {
...mapActions([
'addCountAction',
// 将 `this.addCountAction()` 映射为 `this.$store.dispatch('addCountAction')`
])
}
}
</script>
组合 Action
action 通常是异步的,那么如何知道 action 什么时候结束呢?更重要的是,我们如何才能组合多个 action,以处理更加复杂的异步流程?首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise :
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
}
}
现在你可以在组件中使用:
store.dispatch('actionA').then(() => {
// ...
})
在另外一个 action 中也可以:
actions: {
// ...
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
}
一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行
利用async / await
,组合action
// 假设 getData() 和 getOtherData() 返回的是 Promise
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
Module
- 由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿
- 为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
<!-- 页面路径:store/index.js -->
import Vue from 'vue'
import Vuex from 'vuex'
import moduleA from '@/store/modules/moduleA'
import moduleB from '@/store/modules/moduleB'
Vue.use(Vuex)
export default new Vuex.Store({
modules:{
moduleA,moduleB
}
})
更多推荐
所有评论(0)