1. What is vuex
Vuex is a state management model + library developed specifically for 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.
2. When to use Vuex
- Multiple components depend on the same state.
- Behaviors from different components need to change the same state.
Vuex can help us manage shared state and comes with more concepts and frameworks. This requires a trade-off between short-term and long-term benefits. If you are not planning to develop large single page applications, use Vuex
It may be tedious and redundant. If you need to build a medium-to-large single page application, you will most likely consider how to better manage state outside of components, and Vuex will be a natural choice.
3. Build a vuex environment
Install:
npm install vuex@next --save
Create a file:src/store/
// Introduce Vue core libraryimport Vue from 'vue' // Introduce Vueximport Vuex from 'vuex' //Apply Vuex plug-in(Vuex) //Prepare actions object--response to user actions in componentconst actions = {} //Prepare the mutation object---Modify the data in the stateconst mutation = {} //Prepare the state object---Save specific dataconst state = {} // Create and expose storeexport default new ({ actions, mutation, state })
existPass in when creating vm
store
Configuration Items
...... // Introduce storeimport store from './store' ...... //Create vmnew Vue({ el: '#app', render: h => h(app), store })
4. Five cores
Basic use:
Initialize data, configureaction
, configurationmutations
, operation files
// Introduce the Vuex core libraryimport Vue from 'vue' // Introduce Vueximport Vuex from 'vuex' // Quote Vuex(Vuex) const actions = { //Respond to actions in the component jia(context, value) { ('JIA',value) }, jian(context, value) { ('JIAN', value) } } const mutations = { //Execute plus JIA(state, value) { += value } } // Initialize the dataconst state = { sum:0 } //Create and expose storeexport default new ({ actions, mutations, state })
Read data from vuex in the component:$
Modify data in vuex in the component:$('Method Name in Action', Data)
or$('Method name in mutation', data)
Note: If there is no network request or other business logic, the component can also pass through a ct ion s, neither write d is p at c h, and write c o m m i t directly. Note: If there is no network request or other business logic, the component can also pass actions, neither write dispatch, and write commit directly. Note: If there is no network request or other business logic, the component can also pass through actions, neither write dispatch, and write commit directly.
State
Used to initialize data, provide a unique public data source, and all shared data are placed in the store state for storage, similar to data
Pass within the componentthis.$
Visited.
Pass within HTML$
Visited.
Mutation
The only way to change the state in Vuex's store is to commitmutation
。
The mutation in Vuex is very similar to an event: each mutation has a string of event type (type) and a callback function (handler). This callback function is where we actually make the state change, and it will accept state as the first parameter:
mutations: { increment (state) { // Change status ++ } }
Call
Use in components:this.$('increment')
Submit load:this.$('increment',10)
You can pass additional parameters to mutation, which can be a string or an object. Object-style submission method:
this.$({ type: 'increment', amount: 10 })
Note:::mutation must be a synchronous function
Action
Action submits mutation, not a direct change of state. Action can contain any asynchronous operation.
Use-parameters
The Action function accepts a context object with the same method and properties as the store instance, so you can call itSubmit a mutation, or through
and
to get state and getters.
Call
In the component:this.$('increment')
// Distribute in load formthis.$('incrementAsync', { amount: 10 }) // Distribute in object formthis.$({ type: 'incrementAsync', amount: 10 })
getters
Concept: When the data in the state needs to be processed and used, you can use getters to process it.
existAdditional
getters
Configuration
...... const getters = { bigSum(state){ return * 10 } } //Create and expose storeexport default new ({ ...... getters })
Read data from the component:$
Modules
Purpose: Make the code better maintained and make multiple data classifications more clear.
Revise
const countAbout = { namespaced:true, actions:{.....}, mutations:{.....}, state:{......}, getters:{...}, } const personAbout = { namespaced:true, actions:{.....}, mutations:{.....}, state:{......}, getters:{...}, } const store = new ({ modules: { countAbout, personAbout } })
After turning on the namespace, read state data from the component:
// Method 1: Read directly by yourselfthis.$ // Method 2: Read with mapState...mapState('countAbout',['sum','school', 'subject'])
After turning on the namespace, the getters data is read from the component:
// Method 1: Read directly by yourselfthis.$['personAbout/firstPersonName'] // Method 2: Read with mapGetters...mapGetters('countAbout',['bigSum'])
After opening the namespace, call dispatch in the component
// Method 1: Direct dispatchthis.$('personAbout/addPersonWang', person] // Method 2: Read with mapActions...mapActions('countAbout',{incrementOdd: 'jiaOdd', incrementWait: 'jiaWait'})
After opening the namespace, call commit in the component
// Method 1: commit directly by yourselfthis.$('personAbout/ADD_PERSON',person) // Method 2: Read with mapMutations...mapMutations('countAbout',{increment: 'JIA', decrement: 'JIAN'})
5. The use of four map methods
mapState method: used to help us mapstate
The data in it is a computed attribute.
computed: { //Use mapState to generate computed attributes, sum, school, subject (object writing method) ...mapState({sum:'sum', school:'school', subject:'subject'}) //Use mapState to generate computed properties, sum, school, subject (array writing) ...mapState(['sum','school','subject']) }
2.**mapGetters method:** is used to help us mapgetters
The data in it is a computed attribute.
computed: { //Use mapGetters to generate computed attributes, bigSum (object writing method) ...mapGetters({bigSum:'bigSum'}), //Use mapGetters to generate computed properties, bigSum (array writing) ...mapGetters(['bigSum']), }
**mapActions method:** is used to help us generate andaction
The method of dialogue, i.e.: include$(xxx)
Functions of
methods: { //Create with mapActions, incrementOdd, incrementWait (object form) ...mapActions({incrementOdd:'jiaOdd', incrementWait:'jiaWait'}), //Create with mapActions, incrementOdd, incrementWait (array form) ...mapActions(['jiaOdd','jiaWait']), }
mapMutations method: used to help us generate andmutations
The method of dialogue, i.e.: include$(xxx)
Functions of
methods: { //Create with mapMutations, increment, decrement (object form) ...mapActions({increment:'JIA', decrement:'JIAN'}), //Create with mapMutations, JIA, JIAN (array form) ...mapActions(['JIA','JIAN']), }
This is the end of this article about the five core contents of Vuex. For more related core contents of Vuex, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!