- Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Vuex overview
Core Concepts of Store
1. -state: contains the states stored in the store.
2. -getters: Evaluates the return value based on other Getters or states, similar to calculated properties in Vue.
3. -mutation: a group of methods that perform a state change in a store and can only be a synchronous operation.
4. -action: a group of methods that can contain asynchronous operations.
5.- Moudule: Module is a store split Module, each Module has its own state, getters, mutations, actions.
Vuex auxiliary function
There are two auxiliary functions to obtain data in Vuex: mapState, mapGetters,
Mutations and acitonhas functions mapMutations, mapActions.
The first two are used for computed (in computing attributes)
The latter two are used in methods
How to use
Multiple components share the same state (data)
1. Install vuex
Create a store folder ===>index.js
In main.js, import the store object and put it in a new Vue to get the store object through this.$store
2. Use count (share state defined in state) in VUex
this.$store.state.count
3. You cannot directly change the status in store. You can directly change the data that DevTools cannot listen to
4. Mutations change the status simultaneously
The only way to change the Vuex store state: submit mutations–>(this. codestore.com MIT (‘add’))
Calculated properties in Getters Store
// Compute the square of the number
quadratic(state) {
// The first argument, state state
return state.count * state.count
}
Copy the code
2. Filter the data
filterInfo(state) {
return state.info.filter(res= >{
return res.age>18})}Copy the code
- To get the data
info:this.$store.getters.filterInfo
Copy the code
3. If you want to obtain the number of conditions
- {{$store.getters.filterInfo.length}}
4. If you want to enter your own age, just write a method in getters
// Filter data
filterInfo(state, age) {
// You must return a method to pass a value
//age does not return a definite value, but a function
/ / 1.
// return function(age){
// return state.info.filter(res =>{
// return res.age>age
/ /})
// }
/ / 2.
return (age) = > {// The argument can only be passed after return
return state.info.filter(res= > res.age > age)
}
Copy the code
5. Two arguments in getters
// The first state takes the data, and the second geters: that is, the above square root method can be called from getters
testGettes(state,getters){
return getters.quadratic
}
Copy the code
Vuex auxiliary function
Auxiliary function
MapState, used to map data in state to a component’s computed properties
<! -- The first kind --> <! -- Computed attribute names in the component differ from vuEX state names by using object notation --> computed:mapState({cnum:"count",}) <! -- The second kind --> <! -- Array string notation, computed attribute names in components, when consistent with state names in vuEX --> computed:mapState(["count",]) <! -- Third kind --> <! When a component has its own computed attributes, we can use structural notation to incorporate helper functions into computed attributes --> computed:{... mapState({cnum:"count"})},Copy the code
MapGetters is used to map computed properties in the getter to computed properties in the component using mapState
computed:{
// Object expansion, deconstruct mapGetters. mapGetters({// Map the filterInfo of getters in store to the info calculation property on the component
info:"filterInfo"
}),
...mapGetters([ // Array of strings
"getInfoLength"])}mapMutationsMutations map to methods... mapMutations(["add"
]),
// Object notation. mapMutations({// sync, trigger mutations via commit
myadd:"add".// method name: mutation function name
addtwo:"addParms"}), mapActions: mapActions to methods... mapActions({// method name: mutation function name
myasync:"asyncAdd"
})
Copy the code
Modules, the core of Vuex
When the project is relatively large, if there is only one module to maintain the data, then the module will be very large, not particularly high for the maintainability, so vuEX provides module function, we can process VUEX into multiple modules through modules
const myCount={
state: {user: {name:'admin'.pass:'12345'
},
count:10
},
getters:{
},
mutations: {// There is no third argument in module synchronization, (root state)
cAdd(state,paylaod){
console.log(this)
state.count++
}
},
actions: {}}export default new Vuex.Store({
state: {num:2
},
modules: { // Module options
// Reference the myuser module
u:myUser,
c:myCount,
cat
}
})
Copy the code
Use module properties
$store.state. Module name. Property name $store.getters. Module name. The property name $store.com MIT ('Method name')// Synchronize the commit
$store.dispatch('Method name') // Commit asynchronously
Copy the code
Actual combat parsing
The above concept said, it’s time to practice, move!
State,Mutations
Store under the index. Js
import Vue from 'vue'
import Vuex from 'vuex'
// Install the plug-in
Vue.use(Vuex)
export default new Vuex.Store({
state: {// Store the state
// Customize the share status
count:0.stu:[
{id:1001.name:123},
{id:1003.name:'operator rat'},
{id:1004.name:'dream'},].user: {name:'whatever'.sex:'random'}},// The only way to update store state in VUEX is to commit Mutation
mutations: {// Write methods, through mutations, the page plug-in can listen to
add(state){// The first argument to the method is state, which is the object of state
This is the store object
state.count++
},
//state(state in store),(Payload)
addTen(state,ten){// Click add 10
state.count += ten
},
addTwo(state,obj){// Click add 2 to add obj to receive objects
state.count += obj.two
},
// Add a data item to the STU array
addStu(state,payload){
state.stu.push(payload)// Add data to the array
},
updUser(state,age){// Add a new attribute to the stu object
// state.user.age='18
// state.user = {... state.user,'age':12}
Vue.set(state.user,'age'.123)}},actions: {},
modules: {}})Copy the code
Aone components
<template>
<div class="hello">
<h1>Aone components</h1>
<h2>{{$store.state.count}}</h2>
<li>{{$store.state.stu}}</li>
<button @click="addTen">+ 10</button>
<button @click="addStu">Add members</button>
</div>
</template>
<script>
export default {
name: 'aone'.props: {
msg: String.count:Number
},
data() {
return {
stu: {id:1005.name:'test'}}},methods: {
addTen(){
// Trigger the mutations function, specifying additional parameters, and submit it as a string
this.$store.commit('addTen'.10)},addStu(){
this.$store.commit('addStu'.this.stu)
}
},
}
</script>
Copy the code
Hello component
<template>
<div class="hello">
<h1>The helloworld components</h1>
<h2>{{$store.state.count}}</h2>
<h2>{{$store.state.user}}</h2>
<button @click="addTwo">Click on the add 2</button>
<button @click="updUser">Modify the</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld'.props: {
msg: String.count:Number
},
methods: {
addTwo(){
// Trigger the mutations function, specifying additional parameters, and submit as an object
this.$store.commit({
type:'addTwo'.two:2})},updUser(){
// Trigger the mutations function, specifying additional parameters
this.$store.commit({
type:'updUser'}})}},</script>
Copy the code
Actions,Getters
Store under the index. Js
import Vue from 'vue'
import Vuex from 'vuex'
// Install the plug-in
Vue.use(Vuex)
// instantiate and export vuex
export default new Vuex.Store({
state: {
count: 0.info: [{di: 1.name: 'Developer 1'.age: 21
},
{
di: 2.name: 'Developer 2'.age: 22
},
{
di: 3.name: 'Developer 3'.age: 23}},],// Data can only be changed via mutations
mutations: {// If mutation is an asynchronous function, devTools cannot track data changes
// mutations is responsible for simultaneous changes to the status
increment(state, payload) {
// setTimeout(()=>{
state.count += payload
/ /}, 2000)}},// Write asynchronous actions
actions: {//context Context object
asyncIcrement(context, payload) {
setTimeout(() = > {
context.commit('increment', payload)
}, 2000)}},getters: {// Store's calculated properties
// Compute the square of the number
quadratic(state) {
// The first argument, state state
return state.count * state.count
},
// Filter data
filterInfo(state, age) {
// You must return a method to pass a value
//age does not return a definite value, but a function
// return function(age){
// return state.info.filter(res =>{
// return res.age>age
/ /})
// }
return (age) = > {// The argument can only be passed after return
return state.info.filter(res= > res.age > age)
}
},
testGettes(state,getters){
// Call the square root method above
return getters.quadratic
}
},
modules: {}})Copy the code
Myvux components
<template>
<div id="main">
<h2>This is the Myvue component</h2>
<h3>{{$store.state.count}}</h3>
<button @click="add">+ 1</button>
<button @click="asyAdd">Asynchronous + 1</button>
<h2>Get development under age 22</h2>
</div>
</template>
<script>
export default {
methods: {
add(){
this.$store.commit('increment'.5)},asyAdd(){
// Trigger actions asynchrony and pass the parameter
this.$store.dispatch('asyncIcrement'.10)}}}</script>
Copy the code
Myhome components
<template>
<div id="home">
<h2>This is the Home component</h2>
<h3>{{$store.state.count}}</h3>
<h3>Square: {{$store. Getters. Quadratic}}</h3>
<! Getters to filter data -->
<div>
<h3>Gets the value greater than 22</h3>
<li v-for="itme in info">
{{itme}}
</li>
<! -- {{$store.getters.filterInfo.length}} -->// call the above function<h5>{{$store.getters.testGettes}}</h5>
</div>
</div>
</template>
<script>
export default {
data() {
return {
info:this.$store.getters.filterInfo(22)}}}</script>
Copy the code
Auxiliary functions and Modules
Store under the index. Js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count:0.user: {name:'admin'.pass:'123'
},
info: [{di: 1.name: 'Developer 1'.age: 21
},
{
di: 2.name: 'Developer 2'.age: 22}},],getters: {filterInfo(state){
// Filter data greater than 20
return state.info.filter(info= >info.age>22)},getInfoLeng(state,getter){
return getter.filterInfo.length
}
},
mutations: {
add(state){
this.count ++
},
addParms(state,num){
this.count += num
}
},
actions: {
/ / asynchronous
asyncAdd(context){
setTimeout(() = >{
context.commit('add')},2000)}},modules: {}})Copy the code
Mystate component (mapState corresponds to state)
<template>
<div id="mystate">
<! Vuex count -->
<p>{{$store.state.count}}</p>
<! Data: {{num}}</p> -->
<! {{cnum}}</p> -->
<! -- Vuex data -->
<! -- <p>mapstate:{{count}}</p> <p>mapstate:{{user}}</p> -->
<p>cuser:{{ cuser }}</p>
<p>cuser:{{ csuser }}</p>
<p>cnum:{{ cnum }}</p>
<p>The component's own calculated properties: {{cPrice}}</p>
</div>
</template>
<script>
import {mapState} from 'vuex'
// console.log(mapState);
export default {
data() {
return {
// The definition in data is not reactive
num:this.$store.state.count,
price:10}},// Calculate attributes
// computed:{
// cnum(){
// return this.$store.state.count
/ /}
// }
// Use the mapState helper function to automatically generate the calculated properties
// Computed :mapState([// String array notation
The // // attribute name is the same as the vuex state name and can be written as an array
// 'count',// map state count in VUEX to calculated properties
// 'user'
// ])
// Use it as an object
// computed:mapState({
// cuser(state){
The first function // // uses to evaluate attributes is state state in VUEX, so you can retrieve data directly from state
// return state.user//this.$store.user
/ /},
// // short form
// csuser:state => state.user,
// // is equivalent to Tate => state-count
// cnum:'count'
// })
computed: {// The component's own calculated properties
cPrice(){
return '$'+this.price
},
// Calculate attributes mapped by mapState. mapState({cuser(state){
// The first function to calculate attributes is state in VUEX, so you can get data directly from state
return state.user//this.$store.user
},
// Short form
csuser:state= > state.user,
// equivalent to Tate => state.count
cnum:'count'}}})</script>
Copy the code
Mygetter component (mapGetters for Getters)
<template>
<div id="mygetter">
<h3>Mapgetter usage</h3>
<p>{{$store.getters.filterinfo}}</p>
<p>mapgetters:{{info}}</p>
<p>Info: {{getInfoLeng}}</p>
</div>
</template>
<script>
// Get the auxiliary function
import { mapGetters, mapState } from "vuex";
// console.log(mapState);
export default {
computed: {
// Object expander deconstructs mapGetters. mapGetters({// Object notation
// Map the filterInfo of getters in store to the info calculation property on the component
info:'filterInfo'
}),
...mapGetters([// An array of strings
'getInfoLeng'])}};</script>
Copy the code
Mymutations component (MapMutations corresponds to Mutations)
<template>
<div id="mymutations">
<h3>Use mapmutions and MapActions</h3>
<button @click="add">Trigger the add</button>
<button @click="myadd">Trigger myadd</button>
<! Transmit the -- and -- >
<button @click="addtwo(3)">+ 3</button>
<button @click="myasync">Trigger asynchronous</button>
</div>
</template>
<script>
// Get the auxiliary function
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex';
export default {
// Calculate attributes
computed:{
},
/ / method
methods: {
This is not necessary to trigger methods defined by the mutation function
// clickAdd(){
// this.$store.commit('add')
// }
// Trigger asynchrony
myasync(){
this.$store.dispantch('asyncAdd')},// The use of string arrays. mapMutations(['add'
]),
// Object notation. mapMutations({// The synchronization method fires mutauions with commit
myadd:'add'.// method name: mutation function name
addtwo:'addParms'
}),
/ / asynchronous. mapActions({myasync:'asyncAdd'}})},</script>
Copy the code
The use of Modules
<script>
/ / vuex file
import Vue from 'vue'
import Vuex from 'vuex'
import myUser from './myuser'
import cat from './cat'
Vue.use(Vuex)
// const myUser={
// }
export default new Vuex.Store({
modules: {// Module options
/ / introduction
u:myUser,
cat
}
})
</script>-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- here is a display page<template>
<div class="modules">
<! -- Extra layer of u -->
<h4>User info: {{$store.state.u.user}}</h4>
<h4>{{$store.state.cat.mycat}}</h4>
</div>
</template>
Copy the code
At the end
If it is helpful to you, I hope I can give 👍 comment collection three even!
If you want to make friends with bloggers, you can go to 🌹 and leave a comment if you have any questions.
Bloggers are honest and answer questions for free ❤