current position:Home>[vue2-sgg v] vuex

[vue2-sgg v] vuex

2022-04-29 07:23:34xbd_ zc

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 .

Github Address

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

image-20220426224825047

vuex It doesn't belong to any plug-ins , You can provide data to any component , modify api

image-20220426225057265

5.1.3,vuex Schematic diagram

image-20220426230216994

  • Actions, Mutations, State,
    • These three are all objects {}
    • All three are by store Leader Such as :$store.Actions

image-20220426231938527

  • 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]
  1. 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
    })
    
  2. stay main.js Created in vm Time passes in store Configuration item

    ......
    // introduce store
    import store from './store'
    ......
    
    // establish vm
    new Vue({
          
    	el:'#app',
    	render: h => h(App),
    	store
    })
    

5.3,vuex Basic use

  1. Initialization data 、 To configure actions、 To configure mutations, Operation file store.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,
    })
    
  2. Read... In component vuex Data in :$store.state.sum

  3. 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 writing commit

5.4,getters Use

Be similar to vue Medium computed Compute properties

  1. Concept : When state When the data in the needs to be processed and then used , have access to getters machining .

  2. stay store.js Middle append getters To configure

    ......
    
    const getters = {
          
    	bigSum(state){
          
    		return state.sum * 10
    	}
    }
    
    // Create and expose store
    export default new Vuex.Store({
          
    	......
    	getters
    })
    
  3. Read data from component :$store.getters.bigSum

5.5. four map Use of methods

  1. mapState Method : Used to help us map state The data in is the calculation attribute

    computed: {
          
        // 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']),
    },
    
  2. mapGetters Method : Used to help us map getters The data in is the calculation attribute

    computed: {
          
        // 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'])
    },
    
  3. mapActions Method : Used to help us generate and actions The method of dialogue , namely : contain $store.dispatch(xxx) Function of

    methods:{
          
        // by mapActions Generate :incrementOdd、incrementWait( Objects form )
        ...mapActions({
          incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    
        // by mapActions Generate :incrementOdd、incrementWait( Array form )
        ...mapActions(['jiaOdd','jiaWait'])
    }
    
  4. mapMutations Method : Used to help us generate and mutations The method of dialogue , namely : contain $store.commit(xxx) Function of

    methods:{
          
        // 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

vue-sgg-5-5

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

  1. Purpose : Make the code more maintainable , Make a variety of data classification more clear .

  2. 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
      }
    })
    
  3. 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']),
    
  4. 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'])
    
  5. 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'})
    
  6. 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

vue-sgg-5-7

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

Random recommended