import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
count: 0
},
getters: {
get_count: state => {
return state.count+1;
}
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})getters中以get_开头 如:get_count
mutations中以mut_开头 如:mut_count
actions中以act_开头 如:act_count
getters,直接从store.state中取值即可
state 就类似于 data 用来保存状态的
this.$store.state.count;加工处理状态的数据 返回新数据
this.$store.getters.get_count;更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:
store.commit('increment')附带参数
mutations: {
mut_increment (state, n) {
state.count += n
}
}调用方式
store.commit('mut_increment', 10)传对象
mutations: {
mut_increment (state, payload) {
state.count += payload.amount
}
}调用方式
store.commit('mut_increment', {
amount: 10
})或者对象方式提交
store.commit({
type: 'mut_increment',
amount: 10
})官方文档:https://vuex.vuejs.org/zh/guide/actions.html
Action 类似于 mutation,不同在于:
Action 通过 store.dispatch 方法触发:
store.dispatch('mut_increment')来看一个更加实际的购物车示例,涉及到调用异步 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)
)
}
}注意我们正在进行一系列的异步操作,并且通过提交 mutation 来记录 action 产生的副作用(即状态变更)
this.$store.state.变量 = xxx;this.$store.dispatch(actionType, payload)this.$store.commit(commitType, payload) 共同点: 都能够修改state里的变量,并且是响应式的(能触发视图更新)
不同点:
若将vue创建 store 的时候传入 strict: true, 开启严格模式,那么任何修改state的操作,只要不经过mutation的函数,vue就会
throw error : [vuex] Do not mutate vuex store state outside mutation handlers。
使用commit提交到mutation修改state的优点:
vuex能够记录每一次state的变化记录,保存状态快照,实现时间漫游/回滚之类的操作。
官方要求最好设置严格模式,并且每次都要commit来修改state,而不能直接修改state,以便于调试等。
下载依赖
npm install vuex-persistedstate --save引入及配置:在store下的index.js中
import createPersistedState from "vuex-persistedstate"
const store =new Vuex.Store({
// ...
plugins: [createPersistedState()]
})默认存储到localStorage
想要存储到sessionStorage,配置如下
import createPersistedState from "vuex-persistedstate"
conststore = newVuex.Store({
// ...
plugins: [createPersistedState({
storage:window.sessionStorage
})]
})默认持久化所有state
指定需要持久化的state,配置如下
import createPersistedState from "vuex-persistedstate"
conststore = newVuex.Store({
// ...
plugins: [createPersistedState({
storage:window.sessionStorage,
reducer(val) {
return {
// 只储存state中的assessmentData
assessmentData: val.assessmentData
}
}
})]
})