vue--vuex的使用和理解

vuex解决了什么问题?

解决了单页面应用的状态管理,也就是多组件之间的数据共享问题。

同时还有什么问题?

Vuex的状态存储不能持久化,也就是一刷新页面,vuex的store中存的数据就丢失了

解决问题

使用vuex-persisit,可以直接将状态保存至 cookie 或者 localStorage 中

npm install --save vuex-persist

index.js

import Vue from 'vue';
import Vuex from 'vuex';
import control from './module/control'
import VuexPersistence from 'vuex-persist'
Vue.use(Vuex)
//创建一个对象并进行配置
const vuexLocal = new VuexPersistence({
//storage属性:可传localStorage, sessionStorage, localforage 或者你自定义的存储对象. 接口必须要有get和set. 默认是: window.localStorage
  storage: window.localStorage,
  //要持久化的模块列表。
  modules: ['control'],
})
const store = new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    control
  },
  //引入进vuex插件
  plugins: [vuexLocal.plugin]
});

export default store;

在这里插入图片描述

Vuex.Store

一般我们在项目中使用一个 Vuex.Store实例。创建store实例的构造器有8个参数(构造器选项)

state,
mutation,
actions,
getters,
modules,
plugins,
strict,
devtools

Mutation

mutation就是修改store中的状态的地方,也就是提交mutation,就像提交一个事件

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
  //定义事件
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})


提交事件

store.commit('increment')

提交荷载

你可以向 store.commit 传入额外的参数,即 mutation 的 载荷(payload)

// ...
mutations: {
  increment (state, n) {
    state.count += n
  }
}
store.commit('increment', 10)
//在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:
// ...
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
store.commit('increment', {
  amount: 10
})

mutation 都是同步事务

Mutation 必须是同步函数

在组件中提交Mutation

你可以在组件中使用 this.$store.commit(‘xxx’) 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

import { mapMutations } from 'vuex'

export default {
  // ...
  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')`
    })
  }
}

也就是在vue代码的组件代码,在methods部分中中可以使用this.increment()第二种写法就是this.add()。如果有参数就传入参数就行,只传荷载参数就行

Actions

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态。
  • Action 可以包含任意异步操作。
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。 context 对象不是 store 实例本身

参数解构来简化代码

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

在组件中分发 Action

大概意思就是调用actions里面的函数

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}

组合Action 官方文档

如何才能组合多个 action,以处理更加复杂的异步流程?

目前理解的话,就是在actions的函数里面调用其他actions的函数

首先,你需要明白 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')
    })
  }
}

最后,如果我们利用 async / await (opens new window),我们可以如下组合 action:

// 假设 getData() 和 getOtherData() 返回的是 Promise

actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}

一个 store.dispatch 在不同模块中可以触发多个 action 函数。在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值