This time I will show you how to use vuex in an advanced way, and what are the precautions for advanced use of vuex. The following is a practical case, let's take a look.
1. Getter
Let’s first recall the code of the previous articlecomputed:{ getName(){ return this.$store.state.name } }
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ // 类似 vue 的 data state: { name: 'oldName' }, // 类似 vue 的 computed -----------------以下5行为新增 getters:{ getReverseName: state => { return state.name.split('').reverse().join('') } }, // 类似 vue 里的 mothods(同步方法) mutations: { updateName (state) { state.name = 'newName' } } })
computed:{ getName(){ return this.$store.getters.getReverseName } }
2. actions and $dispatch
If you are careful, you must have noticed that the mutations header in my previous code has comments similar to the methods (synchronous methods) in vueWhy should it be after methods? What about the synchronous method? Mutation can only be a synchronous function, can only be a synchronous function, can only be a synchronous function!! Please see the explanation of vuex: Now imagine that we are debugging an app and Observe the mutation log in devtool. Every time a mutation is recorded, devtools needs to capture snapshots of the previous state and the next state. However, in the above example the callback in the asynchronous function in the mutation makes this impossible: because when the mutation fires, thecallback function has not yet been called, devtools does not know when the callback function actually Called - Essentially any state changes made within the callback function are untraceable. So what if we want to trigger an asynchronous operation? The answer is: action $dispatch, we continue to modify the code below store/index.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ // 类似 vue 的 data state: { name: 'oldName' }, // 类似 vue 的 computed getters:{ getReverseName: state => { return state.name.split('').reverse().join('') } }, // 类似 vue 里的 mothods(同步方法) mutations: { updateName (state) { state.name = 'newName' } }, // 类似 vue 里的 mothods(异步方法) -------- 以下7行为新增 actions: { updateNameAsync ({ commit }) { setTimeout(() => { commit('updateName') }, 1000) } } })
methods: { rename () { this.$store.dispatch('updateNameAsync') } }
export default { state: { ... }, getters: { ... }, mutations: { ... }, actions: { ... } }
export default { state: { ... }, getters: { ... }, mutations: { ... }, actions: { ... } }
import moduleA from './moduleA' import moduleB from './moduleB' export default new Vuex.Store({ modules: { moduleA, moduleB } })
How to use v-model and promise to implement the vue pop-up component
How to use JS implements file drag and drop upload
The above is the detailed content of How to use vuex advancedly. For more information, please follow other related articles on the PHP Chinese website!