核心概念
Vuex全局的数据管理,同样是响应式,只能通过自身的mutation改变数据,可追溯数据的改变,异步则需要在多一层,action中处理异步在触发mutation改变数据的变化。
state
具有响应式的数据,任何组件都可以获取 this.$store.state获取相关数据,获取多个state中的数据,可用mapState简写,也就是
computed:{
a(){
return this.$store.state.a
},
b(){
return this.$store.state.b
}
}
import { mapState } from 'vuex'
....
computed:{
...mapState(['a','b'])
}
getter
与vue中computed类型,state数据不发生改变的话,getters中不会重新计算,第一个参数为state,获取state的相关数据,this.$store.getters中获取,同样也有简写的方式mapGetters。
mutations
vuex中所有的数据只能通过mutation去改变state中的响应式数据,但是mutations只能处理同步,不能处理异步,第一个参数为响应式数据中的state,后面的参数,及触发该函数传进来的参数,通过this.store.commit({type:'increment',amount:10})调用该函数,同样也可以使用简写的方式mapMutations,另外我们可以使用ES2015风格的计算属性命名功能来使用一个常量作为函数名
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
//或者
import { SOME_MUTATION } from '/name'
mutations: {
[SOME_MUTATION] (state) {
// 变更状态
state.count++
}
}
//对应位置去调用即可
this.$store.commit('increment')
或者
import { mapMutations } from 'vuex'
methods:{
...mapMutations({
a: 'increment'
})
}
直接调用a即可
actions
action中可以处理异步,接口请求等相关代码,第一个参数是context是个对象,里面有state,commit等属性或方法,再触发mutations,commit('increment',1),外部通过dispatch去触发即可,同样也可以通过
// 以载荷形式分发
store.dispatch('incrementAsync', {
amount: 10
})
// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
})
也有简写的方式mapActions,
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')`
})
}
}
你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch 仍旧返回 Promise
store.dispatch('actionA').then(() => {
// ...
})
actions: {
// ...
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
}
利用 [async / await],我们可以如下组合 action:
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
Vuex状态共享,但是刷新数据就会没有,恢复初始的值,若想数据持久化,需要将其存放再浏览器中,浏览器常见的储存有cookie,session,location,其中有插件可满足,一般的插件有### vuex-persistedstate和vuex-persist
第一种 vuex-persistedstate插件
安装
npm install vuex-persistedstate --save
npm install vuex-persistedstate --save
1.使用vuex-persistedstate默认存储到localStorage
- 引入及配置:在
store下的index.js中
import createPersistedState from "vuex-persistedstate"
const store =newVuex.Store({
state: {},
mutations: {},
actions: {},
plugins: [createPersistedState()]
})
2.使用vuex-persistedstate存储到sessionStorag
- 引入及配置:在
store下的index.js中
import createPersistedState from "vuex-persistedstate"
const store = newVuex.Store({
state: {},
mutations: {},
actions: {},
plugins: [createPersistedState({
storage:window.sessionStorage
})]
}
3.使用vuex-persistedstate指定需要持久化的state
- 引入及配置:在
store下的index.js中
import createPersistedState from "vuex-persistedstate"
const store = newVuex.Store({
state: {},
mutations: {},
actions: {},
plugins: [createPersistedState({
storage:window.sessionStorage,
reducer(val) {
return {
// 只储存state中的token
assessmentData: val.token
}
}
})]
第二种 引入vuex-persist 插件,它就是为 Vuex 持久化存储而生的一个插件。不需要你手动存取 storage ,而是直接将状态保存至 cookie 或者 localStorage 中。
安装:
npm install --save vuex-persist
or
yarn add vuex-persist
import VuexPersistence from 'vuex-persist'
先创建一个对象并进行配置:
const vuexLocal = new VuexPersistence({
storage: window.localStorage
})
引入进vuex插件:
const store = new Vuex.Store({
state: {},
mutations: {},
actions: {},
plugins: [vuexLocal.plugin]
})
具体做法到插件网页上操作。