current position:Home>[vue2-sgg v] vuex
[vue2-sgg v] vuex
2022-04-29 07:23:34【xbd_ zc】
List of articles
5.1 understand vuex
5.1.1 vuex What is it?
Concept
Specialized in Vue Implement centralized state in ( data ) The one who manages Vue plug-in unit , Yes vue The shared state of multiple components in the application is managed in a centralized way ( read / Write ), It is also a way of communication between components , And it is suitable for communication between any components .
5.1.2 When to use Vuex( share )
1. Multiple components depend on the same state
2. Behaviors from different components need to change the same state .
If you want to transfer data between components
vuex It doesn't belong to any plug-ins , You can provide data to any component , modify api
5.1.3,vuex Schematic diagram
- Actions, Mutations, State,
- These three are all objects {}
- All three are by store Leader Such as :$store.Actions
- If the parameters are specified , It can be downloaded from Vue Components direct commit To Mutations Processing data
5.2, build vuex Environmental Science
- Vue2 in , Use Vuex Of 3 edition
- Vue3 in , Use Vuex Of 4 edition
What we use here is vue2, So install vuex3
npm i [email protected]
create a file :
src/store/index.js
// introduce Vue Core library import Vue from 'vue' // introduce Vuex import Vuex from 'vuex' // application Vuex plug-in unit Vue.use(Vuex) // Get ready actions object —— Respond to user actions in the component const actions = { } // Get ready mutations object —— modify state Data in const mutations = { } // Get ready state object —— Save specific data const state = { } // Create and expose store export default new Vuex.Store({ actions, mutations, state })
stay
main.js
Created in vm Time passes instore
Configuration item...... // introduce store import store from './store' ...... // establish vm new Vue({ el:'#app', render: h => h(App), store })
5.3,vuex Basic use
Initialization data 、 To configure
actions
、 To configuremutations
, Operation filestore.js
// introduce Vue Core library import Vue from 'vue' // introduce Vuex import Vuex from 'vuex' // quote Vuex Vue.use(Vuex) const actions = { // Respond to the actions added in the component jia(context,value){ // console.log('actions Medium jia Is called the ',miniStore,value) context.commit('JIA',value) }, } const mutations = { // Executive plus JIA(state,value){ // console.log('mutations Medium JIA Is called the ',state,value) state.sum += value } } // Initialization data const state = { sum:0 } // Create and expose store export default new Vuex.Store({ actions, mutations, state, })
Read... In component vuex Data in :
$store.state.sum
Component vuex Data in :
$store.dispatch('action Method name in ', data )
or$store.commit('mutations Method name in ', data )
remarks : If there is no network request or other business logic , Components can also cross actions, Not to write
dispatch
, Direct writingcommit
5.4,getters Use
Be similar to vue Medium computed Compute properties
Concept : When state When the data in the needs to be processed and then used , have access to getters machining .
stay
store.js
Middle appendgetters
To configure...... const getters = { bigSum(state){ return state.sum * 10 } } // Create and expose store export default new Vuex.Store({ ...... getters })
Read data from component :
$store.getters.bigSum
5.5. four map Use of methods
mapState Method : Used to help us map
state
The data in is the calculation attributecomputed: { // With the help of mapState Generate calculated properties :sum、school、subject( Object writing ) ...mapState({ sum:'sum',school:'school',subject:'subject'}), // With the help of mapState Generate calculated properties :sum、school、subject( Array writing ) ...mapState(['sum','school','subject']), },
mapGetters Method : Used to help us map
getters
The data in is the calculation attributecomputed: { // With the help of mapGetters Generate calculated properties :bigSum( Object writing ) ...mapGetters({ bigSum:'bigSum'}), // With the help of mapGetters Generate calculated properties :bigSum( Array writing ) ...mapGetters(['bigSum']) },
mapActions Method : Used to help us generate and
actions
The method of dialogue , namely : contain$store.dispatch(xxx)
Function ofmethods:{ // by mapActions Generate :incrementOdd、incrementWait( Objects form ) ...mapActions({ incrementOdd:'jiaOdd',incrementWait:'jiaWait'}) // by mapActions Generate :incrementOdd、incrementWait( Array form ) ...mapActions(['jiaOdd','jiaWait']) }
mapMutations Method : Used to help us generate and
mutations
The method of dialogue , namely : contain$store.commit(xxx)
Function ofmethods:{ // by mapActions Generate :increment、decrement( Objects form ) ...mapMutations({ increment:'JIA',decrement:'JIAN'}), // by mapMutations Generate :JIA、JIAN( Objects form ) ...mapMutations(['JIA','JIAN']), }
remarks :mapActions And mapMutations When using , If parameters need to be passed : Pass good parameters when binding events in the template , Otherwise, the parameter is the event object .
5.6, Case study

vuex To configure ,store/index.js
// This file is used to create Vuex At the core of store
import Vue from 'vue'
// introduce Vuex
import Vuex from 'vuex'
// application Vuex plug-in unit
Vue.use(Vuex)
// Get ready actions—— Used to respond to actions in components
const actions = {
/* jia(context,value){ console.log('actions Medium jia Is called the ') context.commit('JIA',value) }, jian(context,value){ console.log('actions Medium jian Is called the ') context.commit('JIAN',value) }, */
jiaOdd(context,value){
console.log('actions Medium jiaOdd Is called the ')
if(context.state.sum % 2){
context.commit('JIA',value)
}
},
jiaWait(context,value){
console.log('actions Medium jiaWait Is called the ')
setTimeout(()=>{
context.commit('JIA',value)
},500)
}
}
// Get ready mutations—— For operation data (state)
const mutations = {
JIA(state,value){
console.log('mutations Medium JIA Is called the ')
state.sum += value
},
JIAN(state,value){
console.log('mutations Medium JIAN Is called the ')
state.sum -= value
},
ADD_PERSON(state,value){
console.log('mutations Medium ADD_PERSON Is called the ')
state.personList.unshift(value)
}
}
// Get ready state—— For storing data
const state = {
sum:0, // Current and
school:' Somersault Kindergarten ',
subject:' Somersault ',
personList:[
{
id:'001',name:' Zhang San '}
]
}
// Get ready getters—— Is used to state Process the data in
const getters = {
bigSum(state){
return state.sum*10
}
}
// Create and expose store
export default new Vuex.Store({
actions,
mutations,
state,
getters
})
Sum up Count.vue
<template>
<div>
<h1> The current sum is :{
{
sum}}</h1>
<h3> The current summation enlarges 10 Times :{
{
bigSum}}</h3>
<h3> I am here {
{
school}}, Study {
{
subject}}</h3>
<h3 style="color:red">Person The total number of components is :{
{
personList.length}}</h3>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment(n)">+</button>
<button @click="decrement(n)">-</button>
<button @click="incrementOdd(n)"> The current sum is odd plus </button>
<button @click="incrementWait(n)"> Wait a minute </button>
</div>
</template>
<script>
import {
mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
name:'Count',
data() {
return {
n:1, // The number selected by the user
}
},
computed:{
// With the help of mapState Generate calculated properties , from state Read data from .( Array writing )
...mapState(['sum','school','subject','personList']),
// With the help of mapGetters Generate calculated properties , from getters Read data from .( Array writing )
...mapGetters(['bigSum'])
},
methods: {
// With the help of mapMutations Generate the corresponding method , Method is called commit To contact mutations( Object writing )
...mapMutations({
increment:'JIA',decrement:'JIAN'}),
// With the help of mapActions Generate the corresponding method , Method is called dispatch To contact actions( Object writing )
...mapActions({
incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
},
mounted() {
// const x = mapState({he:'sum',xuexiao:'school',xueke:'subject'})
// console.log(x)
},
}
</script>
<style lang="css">
button{
margin-left: 5px;
}
</style>
Person.vue
<template>
<div>
<h1> Personnel list </h1>
<h3 style="color:red">Count Component summation is :{
{
sum}}</h3>
<input type="text" placeholder=" Please enter a name " v-model="name">
<button @click="add"> add to </button>
<ul>
<li v-for="p in personList" :key="p.id">{
{
p.name}}</li>
</ul>
</div>
</template>
<script>
import {
nanoid} from 'nanoid'
export default {
name:'Person',
data() {
return {
name:''
}
},
computed:{
personList(){
return this.$store.state.personList
},
sum(){
return this.$store.state.sum
}
},
methods: {
add(){
const personObj = {
id:nanoid(),name:this.name}
this.$store.commit('ADD_PERSON',personObj)
this.name = ''
}
},
}
</script>
5.7,vuex modularization
Every vuex The module only processes the content of the corresponding component , Use namespace distinguish
namespaced:true
1, modularization + Namespace
Purpose : Make the code more maintainable , Make a variety of data classification more clear .
modify
store.js
const countAbout = { namespaced:true,// Open namespace state:{ x:1}, mutations: { ... }, actions: { ... }, getters: { bigSum(state){ return state.sum * 10 } } } const personAbout = { namespaced:true,// Open namespace state:{ ... }, mutations: { ... }, actions: { ... } } const store = new Vuex.Store({ modules: { countAbout, personAbout } })
After opening the namespace , Read... In component state data :
// Mode one : Read directly by yourself this.$store.state.personAbout.list // Mode two : With the help of mapState Read : ...mapState('countAbout',['sum','school','subject']),
After opening the namespace , Read... In component getters data :
// Mode one : Read directly by yourself this.$store.getters['personAbout/firstPersonName'] // Mode two : With the help of mapGetters Read : ...mapGetters('countAbout',['bigSum'])
After opening the namespace , Call in component dispatch
// Mode one : Own direct dispatch this.$store.dispatch('personAbout/addPersonWang',person) // Mode two : With the help of mapActions: ...mapActions('countAbout',{ incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
After opening the namespace , Call in component commit
// Mode one : Own direct commit this.$store.commit('personAbout/ADD_PERSON',person) // Mode two : With the help of mapMutations: ...mapMutations('countAbout',{ increment:'JIA',decrement:'JIAN'}),
2, Case study
2.1,vuex modular
countOptions.js
export default {
namespaced:true,
actions:{
incrementOdd(context,value){
if (context.state.sum % 2){
context.commit('INCREMENT',value)
}
},
incrementWait(context,value){
setTimeout(()=>{
context.commit('INCREMENT',value)
},500)
}
},
mutations:{
INCREMENT(state,value){
state.sum += value
},
DECREMENT(state,value){
state.sum -= value
},
},
state:{
sum:0},
getters:{
bigSum(state){
return state.sum*10
}
}
}
personOptions.js
import {
nanoid} from "nanoid";
import axios from "axios";
export default {
namespaced:true,
actions:{
addWang(context,value){
// console.log(value.indexOf(" king ")===0)
if (value.indexOf(" king ")===0){
const personObj = {
id:nanoid(),name:value}
context.commit('ADD_PERSON',personObj)
}else {
alert(" The addition must start with Wang ")
}
},
addPersonServer(context){
axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(
response =>{
const personObj = {
id:nanoid(),name:response.data}
context.commit('ADD_PERSON',personObj)
},
error =>{
console.log(error.message)
}
)
}
},
mutations:{
ADD_PERSON(state,value){
state.persons.unshift(value)
}
},
state:{
persons:[
{
id:'001',name:' Zhang San '}
]
},
getters:{
firstName(state){
return state.persons[0].name
}
}
}
index.js
// This file is used to create vuex The core of store
import Vuex from "vuex";
// introduce Vue
import Vue from "vue";
// application Vuex plug-in unit
Vue.use(Vuex)
import countOptions from "@/store/countOptions";
import personOptions from "@/store/personOptions";
// Create and expose store
export default new Vuex.Store({
modules:{
countAbout:countOptions,
personAbout:personOptions
}
})
2.2, Components
Count.vue
<template>
<div>
<h1> The current sum is :{
{
sum}}</h1>
<h1> Current and methods 10 times :{
{
bigSum}}</h1>
<h3 style="color: red"> share :Person The number of components is :{
{
persons.length}}</h3>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment(n)">+</button>
<button @click="decrement(n)">-</button>
<button @click="incrementOdd(n)"> The current sum is odd plus </button>
<button @click="incrementWait(n)"> Wait a minute </button>
</div>
</template>
<script>
import {
mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
// eslint-disable-next-line vue/multi-word-component-names
name:'Count',
data() {
return {
n:1, // The number selected by the user
}
},
methods: {
...mapMutations('countAbout',{
increment:'INCREMENT',decrement:'DECREMENT'}),
...mapActions('countAbout',['incrementOdd','incrementWait'])
},
computed:{
...mapState('countAbout',['sum']),
...mapState('personAbout',['persons']),
...mapGetters('countAbout',['bigSum'])
}
}
</script>
<style lang="css">
button{
margin-left: 5px;
}
</style>
Person.vue
<template>
<div>
<h1> Current user list </h1>
<h3 style="color: red"> share : Count Sum for :{
{
sum}}</h3>
<h4> The name of the first person : {
{
firstName}}</h4>
<input v-model="keyWord"/>
<button @click="add"> add to </button>
<button @click="addWang"> Add a surnamed Wang </button>
<button @click="addPersonServer"> Random addition </button>
<ul>
<li v-for="person in persons" :key="person.id">{
{
person.name}}</li>
</ul>
</div>
</template>
<script>
import {
mapState,mapGetters} from 'vuex'
import {
nanoid} from 'nanoid'
export default {
// eslint-disable-next-line vue/multi-word-component-names
name:'Person',
data() {
return {
keyWord:''
}
},
methods: {
// ...mapMutations({increment:'INCREMENT',decrement:'DECREMENT'}),
// ...mapActions(['incrementOdd','incrementWait'])
add(){
console.log(this)
const personObj = {
id:nanoid(),name:this.keyWord}
this.$store.commit('personAbout/ADD_PERSON',personObj)
this.keyWord = ''
},
addWang(){
this.$store.dispatch('personAbout/addWang',this.keyWord)
this.keyWord = ''
},
addPersonServer(){
this.$store.dispatch('personAbout/addPersonServer')
this.keyWord = ''
}
},
computed:{
...mapState('countAbout',['sum']),
...mapGetters('countAbout',['bigSum']),
...mapState('personAbout',['persons']),
...mapGetters('personAbout',['firstName'])
}
}
</script>
<style lang="css">
button{
margin-left: 5px;
}
</style>
copyright notice
author[xbd_ zc],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290422108222.html
The sidebar is recommended
- How to realize Ethernet wireless communication between 200smartplc?
- Still working on nginx configuration? Try this visual configuration tool. It's really powerful!
- Simple sorting of JavaScript deep copy and shallow copy
- React realizes the communication of brother components by means of message subscription and publication
- React limits props
- Java lesson 30
- Java lesson 29 136 The number 1189 appears only once Maximum number of balloons
- Simple sorting of JavaScript deep copy and shallow copy
- "Geely" new SUV is equipped with frameless doors, and the interior is more beautiful than Mercedes Benz. Can 19 universal accept it?
- Configuration of using less in react project
guess what you like
Expression used in react render
React configuration agent
JQuery sends a post request (a method of connecting PHP variables to strings)
Solve the problem that Django cannot access the local server( http://127.0.0.1:8000/ )Or the problem that the command line execution (Python 3 manage.py runserver 0.0.0.0:8000) does not respond
Summary of the writing method of react router V6
Bipeng ditch, punch in and net red, open-air boundless swimming pool, Ramada hot spring, encounter the beauty of the four seasons
JavaScript gets and modifies elements. What's wrong with not extracting the classlist attribute
Mixed mixin of Vue
Vue + element implements table filtering
Vue router2. 0
Random recommended
- Which one charges less for opening a securities account and how to open the account
- Spring MVC notes 02 domain object sharing data, view, restful, httpmessageconverter, file upload and download
- Httpclient setting timeout
- Command line / Python uses pdf2htmlex to convert PDF to HTML
- [front end three swordsmen III] analysis of JavaScript scalpel Part II
- How to choose the front-end learning path
- Finite element parametric element, calculation, theoretical problems
- Handwritten CSS modules to understand its principle
- Front end browser debugging tips
- Performance problem analysis guide for enterprise JavaScript applications running in production systems
- CSS aspect-ratio All In One
- Actual combat of vue3 project --- Zhihu daily --- details page
- Actual combat of vue3 project --- Zhihu daily --- home page function
- Great Wall Motors is falling endlessly! The boss has lost 150 billion yuan in half a year, and the performance of the new energy sector has improved
- Nginx tips batch shutdown process
- Openresty introduces nginx_ upstream_ check_ Module module
- Nginx multiple servers_ How does name match
- Why does the front end still prompt cannot post, and the error reported by the back end still prompt null pointer?
- HTML Li set margin: 50%, but the width of the outermost div is the standard
- Are there any specific steps to create a prototype, such as JavaScript?
- How does HTML5 display the value obtained from the database in the specified area
- Problems related to nginx rewriting interface
- What happens when you open a CSS file in eclipse without responding
- React download local template can be downloaded locally, but the deployment online download is blank
- @Babel / traverse official example running error: typeerror: traverse is not a function
- The click event of jQuery has no effect
- How to learn from non professional background?
- Usage of API documented as @since 1.8+ less... (Ctrl+F1) Inspection info: This inspection finds all
- Configuration Vue of webpack
- Introduction to nginx (learning notes)
- Is the financial management class of qiniu school true? Can you learn how to manage money in free lessons
- How does Java randomly get elements from a list
- Use of Vue on in Vue
- Use of Vue router
- Vue basic syntax
- Use of webpack
- Vue diff algorithm
- CSS -- Text gradient from top to bottom
- Routing: Vue router
- Leetcode 658. Find K closest elements