vuex has a basic understanding of installation and preliminary use
First, let's look at how components in vue share data
Father to son v-bind
Son to father v-on
Sibling components EventBus
$on the component that receives the data
$emit the component that sends the data
Understanding vuex
It is a mechanism to realize the global state (data) management of components, which can facilitate the sharing of data between components
Benefits of using vuex to uniformly manage state
The shared data can be centrally managed in vuex, which is easy to develop and maintain later
It can efficiently realize the data sharing between components and improve the development efficiency
The data stored in vuex is responsive, which can keep the data synchronized with the page in real time
What kind of data is suitable for storage in vuex
Generally, only the data shared between components need to be stored in vuex, and the private data in the component can still be stored in the data of the component itself
install
npm install vuex --save
Import
import Vuex from vuex Vue.use(Vuex)
Create a store object
const store = new Vuex.Store({ // The data stored in state is the global shared data state:{count:0} })
Mount the store object into the vue instance
new vue({ el:"#app", render:h=>h(app), router, // Mount the created shared data object into the vue instance // All components can directly obtain global data from the store store })
Two ways to use vuex state
State is the only public data source. All shared data should be stored in the state of the store
Component access
The first way of data in state
this.$store.state.Global data name
The second method of data in state
Map the global data required by the current component to the calculated calculation property of the current component by importing the mapState function
// Import mapState functions from vuex on demand import {mapState} from 'vuex' // Map all data to the calculated properties of the current component computed:{ ...mapState(['count']) }
Install vuex when the project is initialized, so that the project will have a store file and a simple project structure by default
After the new project is completed and opened, there is an index.js file in the store file
Open index.js and add a count value into it
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { count: 0 }, })
Create two new files in the components file
Get the count value through state
The code of the first file is as follows
<template> <div> <h3>Current latest count Value is: {{this.$store.state.count}}</h3> <button>+1</button> </div> </template> <script> export default { data () { return {} } } </script>
The code of the second file is as follows
<template> <div> <h3>Current latest count Value is:{{count}}</h3> <button>-1</button> </div> </template> <script> import { mapState } from 'vuex' export default { data () { return {} }, computed: { ...mapState(['count']) } } </script>
These two files are accessed by components to obtain the value of count
Introduce these two components in the app.vue file
Import component register component use component
Rerun project
You can see and get it in the browser interface count is 0
Two usage modes and parameters of station
Mutation is used to change the data in the store
1. The store data can only be changed through mutation, and the data in the store cannot be operated directly
2 in this way, although the operation is a little cumbersome, it can centrally monitor the changes of all data
The first method is commit
Defined in store/index.js
// Define Mutation const store = new Vuex.Store({ state: { count:0 }, mutations: { sub (state) { state.count-- } } })
Triggered on the page in use
// Trigger mutation methods: { handleBtnSub(){ // The first way to trigger mutation this.$store.commit('sub') } }
The function of commit is to call a mutation function
Pass parameters when triggering mutations
mutations:{ subN (state, step) { state.count -= step } }, methods:{ handleBtnSub(){ this.$store.commit('subN',3) } }
The second way to trigger mutation is mapMutations
// Import mapMutations function from vuex on demand import {mapMutations} from 'vuex // Map the required changes function to the methods method of the current component through the imported function methods:{ ...mapMutations(['sub', 'subN']), handleBtnSub () { this.sub() }, handleBtnSubN () { this.subN(3) } } // @click="handleBtnSub" here is equivalent to another method call. You can also directly @ click="sub"
Do not perform asynchronous operations in the mutations function
Two usage methods and parameters of Action
If you change data through asynchronous operation, you must use Action instead of Mutation, but in Action, you still need to change data indirectly by triggering Mutation
The first way to trigger an action is this.$store.dispatch()
Used in store/index.js
Here, an asynchronous task is simulated by a timer
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { count: 0 }, mutations: { add (state) { state.count++ } }, actions: { // You cannot directly modify the data of state in actions. You must trigger a mutation through context.commit() addAsync (context) { setTimeout(() => { context.commit('add') }, 1000) } }, })
Trigger in page
handleBtnAddAsync () { // The dispach function here is specifically used to trigger action this.$store.dispatch('addAsync') }, // @click="handleBtnAddAsync" here is equivalent to another method call. You can also directly @ click="addAsync"
Trigger action asynchronous task carrying parameters
Receive parameters in store/index.js
...Omit reference export default new Vuex.Store({ state: { count: 0 }, mutations: { addN (state, step) { state.count += step } }, actions: { addNAsync (context, step) { setTimeout(() => { context.commit('addN', step) }, 1000) } } })
Trigger transfer parameters in the page
handleBtnAddAsyncN () { this.$store.dispatch('addNAsync', 5) } // @click="handleBtnAddAsyncN" this is equivalent to another method call. You can also directly @ click="addNAsync(5)"
mapActions is the second way to trigger actions
// Import mapActions function from vuex on demand import {mapActions} from 'vuex' // Map the specified actions function to the methods function of the current component methods:{ ...mapActions(['addNAsync']), addAsync () { this.subAsync() } }
@click="handleBtnSubAsync" here is equivalent to another method call, or you can directly @ click="addN"
Two ways to use Getter
Getter is used to process the data in the store to form new data, similar to vue calculation properties
When the data in the store changes, so will the data in the getter
...Introduce ellipsis // Define getter state: { count: 0 }, getters:{ showNum:state=>{ return `The current latest quantity is[ ${state.count}]` } }
The first way to use getters
this.$store.getters.name // <h3>{{$store.getters.showNum}}</h3>
The second way to use getters
On the page to use
// introduce import {mapGetters} from 'vuex' computed: { ...mapGetters(['showNum]) } // <h3>{{showNum}}</h3>