quick get start
1. Install the vuex Library
cnpm install -S vuex
2. Create Vuex.Store
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); const store = new Vuex.Store({ //Component data source, single state attribute state: { clickCount: 0 }, //Equivalent to attribute, encapsulate get state getters: { getClickCount: state => { return state.clickCount; } }, //Method of state change caused by encapsulation mutations: { increment(state) { state.clickCount++; } }, //be similar to mutation,The difference is actions Support asynchronous, not change state directly, but submit to mutation actions: { increment(context) { context.commit('increment') }, async incrementAsync({ commit }) { return new Promise((resolve, reject) => { setTimeout(() => { try { commit('increment'); resolve(new Date().getTime() + ' Successful execution'); } catch (e) { reject(e); } }, 1000) }); } } }); export default store;
3. Vue instance joins store
new Vue({ router: router, store: store, render: h => h(App), }).$mount('#app')
4. The component obtains the store value
<script> import { mapGetters } from "vuex"; export default { computed: mapGetters({ count: ["getClickCount"] }), }; </script>
5. Component trigger update
<script> export default { data() { return { times: 0 }; }, methods: { increment() { this.times++; //Distribute to action this.$store.dispatch("incrementAsync"); //Submit to mutations this.$store.commit("increment"); }, }, }; </script>
analysis
What is Vuex?
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 ensures that the state changes in a predictable way with corresponding rules. Vuex is also integrated into the official debugging tool devtools extension of Vue, which provides advanced debugging functions such as zero configuration time travel debugging, state snapshot import and export, etc.
State - data source
Vuex uses a single state tree - yes, one object contains all the application level states.
Vue calls Vue.use(Vuex) through the store option to inject into each subcomponent (similar to routing)
Component get State
computed: { count () { return this.$store.state.count } }
Or use the auxiliary function mapState
computed: mapState({ // Arrow function can make the code more concise count: state => state.count })
Getter - data encapsulation read (similar property)
Getter accepts state as its first parameter
getters: { doneTodos: state => { return state.todos.filter(todo => todo.done) }, getTodoById: (state) => (id) => { return state.todos.find(todo => todo.id === id) } }
Access through properties
store.getters.doneTodos
Access through method
store.getters.getTodoById(2)
Getters also provides a helper function for easy access (mapGetters)
Mutation - where status changes are made
Defining music
mutations: { increment (state, n) { state.count += n } }
Component triggered change
store.commit('increment', 1)
Mutations also provide auxiliary functions (mapMutations)
import { mapMutations } from 'vuex' export default { // ... methods: { ...mapMutations([ 'increment', // take `this.increment()` Map to `this.$store.commit('increment')` // `mapMutations` Also supports loads: 'incrementBy' // take `this.incrementBy(amount)` Map to `this.$store.commit('incrementBy', amount)` ]), ...mapMutations({ add: 'increment' // take `this.add()` Map to `this.$store.commit('increment')` }) } }
matters needing attention
- Rotation must be a synchronization function
- It's best to initialize all the required properties in your store in advance.
- Use Vue.set or replace the old object when you need to add a new property on the object
Action - encapsulate the rotation
Action is similar to mutation, with the following differences:
- Action submits a mutation, not a direct change of state.
- An Action can contain any asynchronous Action.
Define Action
actions: { increment ({ commit }) { commit('increment') } }
Component distribution Action
store.dispatch('increment')
Supports asynchronous distribution
actions: { async incrementAsync({ commit }) { return new Promise((resolve, reject) => { setTimeout(() => { try { commit('increment'); resolve(new Date().getTime() + ' Successful execution'); } catch (e) { reject(e); } }, 1000) }); } }
Component call asynchronous distribution
this.$store.dispatch("incrementAsync").then( (data) => { console.log(data); }, (err) => { console.log(err); } );
Reference article
For forwarding, please indicate the source: https://www.cnblogs.com/wilson pan/p/12773090.html