This article mainly introduces the use of vuex and the detailed explanation of the method of persisting state. Now I will share it with you and give you a reference.
Vuex is a state management pattern developed specifically for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way.
When we came into contact with vuex, this was the first official guidance we saw.
From this sentence, we can get the following information:
1. vuex is a specialized Flux that exists for vue, just like in the database Like the weak entities, vuex cannot be used without vue. On the contrary, you can see that redux does not exist. Whether it is vue or react, redux can be used. Therefore, the "features" of vuex reflected here, redux has "universality"
2. Centralized management shows that the status of all components in vue exists in vuex
3. When using vuex, you must follow my rules, so that I can track the changes in the state of the component.
The picture above is part of the skeleton of the overall vue project in this article.
vuex uses a single state tree, and our vue application will only contain one store instance. So when we mount the store to the vue instance, we can get the various parts of vuex through this.$store.
import vue from 'vue' import vuex from 'vuex' import mutations from './mutation' import getters from './getter' vue.use(vuex) const state = { isLoading:false } export default new vuex.Store({ state, getters, mutations })
In the index file, we will define the initial value of the state that we need to store in vuex.
For example, I stored an isLoading attribute in the state object above. I plan to use this attribute to identify the loading effect that will be displayed when I request the backend API and disappear after the request is completed. , to ease the user’s waiting mentality.
Generally speaking, the most commonly used method in our projects is the method in mutation.js. Because the only way to change the state in the store in vuex is to submit a mutation.
In vuex, each mutation has a string event type (mutation-type) and a callback function (handler).
This callback function can accept two parameters, the first parameter is state, and the second parameter is the payload of mutation.
//... mutations: { /** * @method:只传入state,修改loading状态 * @param {bool} isLoading:loading状态 */ changeLoading(state) { state.isLoading = !state.isLoading } } store.commit('changeLoading') mutations: { /** * @method:传入state和payload,修改loading状态 * @param {bool} isLoading:loading状态 */ changeLoading(state,payload) { state.isLoading = payload.isLoading } } store.commit('changeLoading',{isLoading: true})
Another way to submit a mutation is to directly use an object containing the type attribute, but I do not recommend this method very much, because the code will be more readable if handled in the above way.
store.commit({ type: 'changeLoading', isLoading: true })
In projects that require multi-person collaboration, we can use constants instead of mutation event types. This is a very common pattern in various Flux implementations. Also keeping these constants in separate files makes collaborative development clear.
// mutation-types.js export const CHANGE_LOADING= 'CHANGE_LOADING' // mutation.js import { CHANGE_LOADING} from './mutation-types' export default{ [CHANGE_LOADING](state,payload){ state.isLoading = payload.isLoading }, }
For defining the event types in mutation-type, I roughly follow the following specifications defined by myself:
1. Because mutation is similar to an event, it starts with a verb
2. Words are connected with underscores
3. The state saved in vuex is marked with RECORD
4. The state cached locally is marked with SAVE
Of course, You can define this specification yourself. As long as you can know the intention of the mutation through mutation-type, it is excellent.
Sometimes we need to derive some status from the state in the store. For example, I mentioned above that we need to display a state during an asynchronous request. Loading with a mask layer, and then I need to display the loading status according to the state below the loading. Without using getters, we will choose to use calculated properties to handle it.
computed: { loadingTxt () { return this.$store.state.isLoading ? '加载中' : '已完成'; } }
However, our loading needs to be used in many components. Then, we either copy the function, or we extract it to a shared function and import it in multiple places - either way is not ideal.
If you use Getter, everything becomes beautiful.
//getter.js export default { loadingTxt:(state) =>{ return state.isLoading ? '加载中' : '已完成'; } };
Just like computed properties, the return value of a getter will be cached according to its dependencies, and will only be recalculated when its dependency values change.
And, Getter can also accept other getters as the second parameter:
export default { loadingTxt:(state) =>{ return state.isLoading ? '加载中' : '已完成'; }, isLoading:(state,getters) => { return 'string' === typeof getters.loadingTxt ? true : false; } };
The getters in the store can be mapped to local calculated properties through the mapGetters auxiliary function
//组件中 import { mapGetters } from 'vuex' export default { data(){ return { //... } }, computed: { // 使用对象展开运算符将 getter 混入 computed 对象中 ...mapGetters([ 'loadingTxt', 'isLoading', // ... ]) } }
The function of action is similar to mutation. They both change the state in the store. However, there are two differences between action and mutation:
1. Action is mainly It deals with asynchronous operations. Mutation must be executed synchronously, but action is not subject to such restrictions. That is to say, in action we can handle both synchronous and asynchronous operations.
2. Action changes state. Finally, by submitting mutation
Take the shopping cart as an example. When we add a product, we need to communicate with the backend first. This involves sku or if the user only adds it but does not Go and place an order.
If the background addition is successful, the front-end will display the newly added product. If it fails, we need to tell the user that the addition failed.
const actions = { checkout ({ state, commit, //rootState }, products) { const savedCartItems = [...state.added] commit(SET_CHECKOUT_STATUS, null) // 置空购物车 commit(SET_CART_ITEMS, { items: [] }) shop.buyProducts( products, //成功 () => commit(SET_CHECKOUT_STATUS, 'successful'), //失败 () => { commit(SET_CHECKOUT_STATUS, 'failed') commit(SET_CART_ITEMS, { items: savedCartItems }) } ) } }
当我们的项目足够大的时候,单一的状态树这个时候就会显得很臃肿了。因为需要用vuex进行状态管理的状态全部集中在一个state对象里面。
所以,当一个东西大了以后,我们就要想办法进行分割,同样的道理,我们熟知的分冶法和分布式其实也是基于这样的一个思想在里面。而vuex提供了module,我们就可以去横向的分割我们的store。
比如说,我在项目中需要去做一个购物车这样的东西,这在电商的项目中也是常见的需求。
//shopCart.js import shop from '../../api/shop' import { ADD_TO_CART, SET_CART_ITEMS, SET_CHECKOUT_STATUS } from '../mutation-types' const state = { added: [], checkoutStatus: null } /** * module getters * @param {Object} state:模块局部state * @param {Object} getters:模块局部getters,会暴露到全局 * @param {Object} rootState:全局(根)state */ const getters = { checkoutStatus: state => state.checkoutStatus, cartProducts: (state, getters, rootState) => { return state.added.map(({ id, quantity }) => { const product = rootState.products.all.find(product => product.id === id) return { title: product.title, price: product.price, quantity } }) }, cartTotalPrice: (state, getters) => { return getters.cartProducts.reduce((total, product) => { return total + product.price * product.quantity }, 0) } } /** * module actions * @param {Object} state:模块局部state * @param {Object} getters:模块局部getters,会暴露到全局 * @param {Object} rootState:全局(根)state */ const actions = { checkout ({ state, commit, //rootState }, products) { const savedCartItems = [...state.added] commit(SET_CHECKOUT_STATUS, null) // 置空购物车 commit(SET_CART_ITEMS, { items: [] }) shop.buyProducts( products, //成功 () => commit(SET_CHECKOUT_STATUS, 'successful'), //失败 () => { commit(SET_CHECKOUT_STATUS, 'failed') commit(SET_CART_ITEMS, { items: savedCartItems }) } ) } } /** * module mutations * @param {Object} state:模块局部state * @param payload:mutation的载荷 */ const mutations = { //用id去查找商品是否已存在, [ADD_TO_CART] (state, { id }) { state.checkoutStatus = null const record = state.added.find(product => product.id === id) if (!record) { state.added.push({ id, quantity: 1 }) } else { record.quantity++ } }, [SET_CART_ITEMS] (state, { items }) { state.added = items }, [SET_CHECKOUT_STATUS] (state, status) { state.checkoutStatus = status } } export default { state, getters, actions, mutations }
在module的定义的局部state,getters,mutation,action中,后三个都会暴露到全局的store中去,这样使得多个模块能够对同一 mutation 或 action 作出响应。就不需要在其他的模块中去定义相同的mutation或action了。
而这里的state是局部的。这也导致后来的持久化无法去处理用module分割后的state。
如同上面的module =》shopCart,
当我们无论是在index.js里面或者其他的module中,shopCart里面的getters或者action或者mutations,我们都可以去使用。
//test.js const state = { isTest:false }; const getters = { isTest :state => state.isTest, checkTestStatus:(state,getters) => { return getters.checkoutStatus; } }; export default { state, getters, } //组件中 ...mapGetters([ 'checkTestStatus' ]) //... created(){ this.checkTestStatus ;//null }
如果说,我就想让我的module里面的定义的全部都是独享的。我们可以使用module的命名空间,通过设置namespaced: true。
//test.js const getters = { // 在这个模块的 getter 中,`getters` 被局部化了 // 你可以使用 getter 的第四个参数来调用 `rootGetters` someGetter (state, getters, rootState, rootGetters) { getters.someOtherGetter // 'test/someOtherGetter' rootGetters.someOtherGetter // 'someOtherGetter' }, someOtherGetter: state => { ... } }; const actions = { // 在这个模块中, dispatch 和 commit 也被局部化了 // 他们可以接受 `root` 属性以访问根 dispatch 或 commit someAction ({ dispatch, commit, getters, rootGetters }) { getters.someGetter // 'test/someGetter' rootGetters.someGetter // 'someGetter' dispatch('someOtherAction') // 'test/someOtherAction' dispatch('someOtherAction', null, { root: true }) // 'someOtherAction' commit('someMutation') // 'test/someMutation' commit('someMutation', null, { root: true }) // 'someMutation' }, someOtherAction ({ state,commit }, payload) { ... } } export default { namespaced: true, state, getters, actions, mutations }
用过vuex的肯定会有这样一个痛点,就是刷新以后vuex里面存储的state就会被浏览器释放掉,因为我们的state都是存储在内存中的。
而像登录状态这样的东西,你不可能一刷新就让用户重新去登录吧!所以,我们会去选择把状态存储到本地。
这样一来问题貌似是解决了,但是当我们需要使用的时候,我们就需要不断的从本地,通过getStore这样的方法去取得我们state。如果需要更新的话,我们又要在mutation里面通过setStore这样的方法去处理它。
虽然,我们的setStore都是在操作了state以后再去调用的,也就是说无论是通过vuex的logger或者vue的dev tool我们都是可以对local里面的状态进行跟踪的,但是,我们无法保证我们每次都记着去写setStore。
这样一来,在共享state的组件中,我们的代码可能就会是这样的。
import { getStore } from '@/util' //组件中 mounted(){ this.foo = getStore('foo'); this.bar = getStore('bar'); //.... }
那么,如何去改进呢?
我们能想到的就是,能不能让state不是保存在内存中,而是存储在本地。
而vuex-persistedstate做了这样的事情,它帮我们将store里面的state映射到了本地环境中。这样一来,我通过提交mutation改变的state,会动态的去更新local里面对应的值。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
在vue 2.x 中使用axios如何封装的get 和post方法
使用node应用中timing-attack存在哪些安全漏洞
The above is the detailed content of Using vuex and persistence. For more information, please follow other related articles on the PHP Chinese website!