Vue Summary - Vuex advanced

Vue summary (VI) -- Vuex advanced

preface

This blog is a further summary based on the previous blog. So I suggest you take a look at the last blog first.

Previous: Vue summary (V) -- Introduction to Vuex

The main contents of this blog include:

  1. getters
  2. mapState and mapGetters
  3. mapMutations and mapActions
  4. Case: multi component data sharing
  5. vuex modular coding

1,getters

1.2 basic use

  1. Concept: when the data in state needs to be processed before use, you can use getters processing (getters is similar to calculating attributes).

  2. In Src / store / index Add getters configuration in JS

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

1.3 example

Transform the [summation case] of the last blog and implement getter.

  • Click the "+" sign to add 1 to sum
  • Click the "-" sign to subtract 1 from sum
  • Click "add if the current sum is odd". If the sum is odd, the sum will be added by 1, otherwise it will remain unchanged
  • Click "wait and add", then wait a few seconds for sum to add 1
  • New features
    • The current sum (sum value) is magnified by 10 times

src/store/index.js

//This file is used to create the most core store in Vuex
import Vue from 'vue'
//Introduce Vuex
import Vuex from 'vuex'
//Apply Vuex plug-ins
Vue.use(Vuex);

//Prepare actions -- used to respond to actions in the component
const actions = {
    //If you don't need business processing, you can bypass actions directly
    /* 
    //plus
    jia(context,value) {
        console.log('actions jia in was called ')
        context.commit('JIA',value)
    },
    //reduce
    jian(context,value) {
        console.log('actions jian in was called ')
        context.commit('JIAN',value)
    }, */
    
    //Odd plus
    jiaOdd(context, value) {
        console.log('actions Medium jiaOdd Called')
        if (context.state.sum % 2) {
            context.commit('JIA', value)
        }
    },
    //Wait a minute
    jiaWait(context, value) {
        console.log('actions Medium jiaWait Called')
        setTimeout(() => {
            context.commit('JIA', value)
        }, 500)
    }
};

//Prepare mutations -- for manipulating data (state)
const mutations = {
    JIA(state, value) {
        console.log('mutations Medium JIA Called');
        state.sum += value
    },
    JIAN(state, value) {
        console.log('mutations Medium JIAN Called');
        state.sum -= value
    }
}

//Prepare state -- used to store data
const state = {
    sum: 0 //Current and
}

//Prepare getters -- used to process the data in state
const getters = {
    bigSum(state) {
        return state.sum * 10
    }
}

//Create and expose store s
export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})

src/main.js

Register the store configuration object.

//Introduce Vue
import Vue from 'vue'
//Introduce App
import App from './App.vue'
//Introducing store
import store from './store'
//Turn off Vue's production prompt
Vue.config.productionTip = false;

//Create vm
new Vue({
    el: '#app',
    render: h => h(App),
    store
})

src/components/Count.vue

<template>
    <div>
        <h1>The current summation is:{{$store.state.sum}}</h1>
        <h3>The current summation magnification is 10 times:{{$store.getters.bigSum}}</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">+</button>
        <button @click="decrement">-</button>
        <button @click="incrementOdd">The current sum is odd plus</button>
        <button @click="incrementWait">Wait a minute</button>
    </div>
</template>

<script>
    export default {
        name: 'Count',
        data() {
            return {
                n: 1, //User selected number
            }
        },
        methods: {
            increment() {
                this.$store.commit('JIA', this.n)
            },
            decrement() {
                this.$store.commit('JIAN', this.n)
            },
            //Odd plus
            incrementOdd() {
                this.$store.dispatch('jiaOdd', this.n)
            },
            //Wait a minute
            incrementWait() {
                this.$store.dispatch('jiaWait', this.n)
            },
        },
        mounted() {
            console.log('Count', this.$store)
        },
    }
</script>

<style lang="css">
    button {
        margin-left: 5px;
    }
</style>

App.vue

<template>
    <div>
        <Count/>
    </div>
</template>

<script>
    import Count from './components/Count'

    export default {
        name: 'App',
        components: {Count},
    }
</script>

2. mapState and mapGetters

2.1 basic usage

To use, first introduce the corresponding components

import {mapState, mapGetters} from 'vuex'
  1. mapState method: it is used to help us map the data in the state to the calculation attribute (generate the calculation attribute of the data in the state)

    computed: {
        //Generate calculation attributes with mapState: sum, school, subject (object writing method)
         ...mapState({sum:'sum',school:'school',subject:'subject'}),
             
        //Generate calculation attributes with mapState: sum, school, subject (array writing method)
        ...mapState(['sum','school','subject']),
    },
    
  2. mapGetters method: used to help us map the data in getters into calculation attributes (generate the calculation attributes of the data in getters)

    computed: {
        //Generate calculation attribute with mapGetters: bigSum (object writing method)
        ...mapGetters({bigSum:'bigSum'}),
    
        //Generate calculation attribute with mapGetters: bigSum (array writing method)
        ...mapGetters(['bigSum'])
    },
    

2.2 example

src/store/index.js

//This file is used to create the most core store in Vuex
import Vue from 'vue'
//Introduce Vuex
import Vuex from 'vuex'
//Apply Vuex plug-ins
Vue.use(Vuex)

//Prepare actions -- used to respond to actions in the component
const actions = {
    /* jia(context,value){
        console.log('actions jia in was called ')
        context.commit('JIA',value)
    },
    jian(context,value){
        console.log('actions jian in was called ')
        context.commit('JIAN',value)
    }, */
    jiaOdd(context, value) {
        console.log('actions Medium jiaOdd Called')
        if (context.state.sum % 2) {
            context.commit('JIA', value)
        }
    },
    jiaWait(context, value) {
        console.log('actions Medium jiaWait Called')
        setTimeout(() => {
            context.commit('JIA', value)
        }, 500)
    }
}
//Prepare mutations -- for manipulating data (state)
const mutations = {
    JIA(state, value) {
        console.log('mutations Medium JIA Called')
        state.sum += value
    },
    JIAN(state, value) {
        console.log('mutations Medium JIAN Called')
        state.sum -= value
    }
}
//Prepare state -- used to store data
const state = {
    sum: 0, //Current and
    school: 'Hamapi',
    subject: 'back-end'
}
//Prepare getters -- used to process the data in state
const getters = {
    bigSum(state) {
        return state.sum * 10
    }
}

//Create and expose store s
export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})

Count.vue

<template>
    <div>
        <h1>The current summation is:{{sum}}</h1>
        <h3>The current summation magnification is 10 times:{{bigSum}}</h3>
        <h3>I am here{{school}},study{{subject}}</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">+</button>
        <button @click="decrement">-</button>
        <button @click="incrementOdd">The current sum is odd plus</button>
        <button @click="incrementWait">Wait a minute</button>
    </div>
</template>

<script>
    //Import corresponding components
    import {mapState, mapGetters} from 'vuex'

    export default {
        name: 'Count',
        data() {
            return {
                n: 1, //User selected number
            }
        },
        computed: {
            //It is up to the programmer to write the calculation properties himself
            /* sum(){
                return this.$store.state.sum
            },
            school(){
                return this.$store.state.school
            },
            subject(){
                return this.$store.state.subject
            }, */

            //Generate calculation properties with mapState and read data from state. (object writing)
            //he, xuexiao and xueke are the names of calculated attributes, which are written on the page
            //sum, school and subject correspond to the attribute names in state
           //... mapState({what is the name of the generated calculated attribute (left): 'which attribute in state is generated for'})
            // ...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),

            //Generate calculation properties with mapState and read data from state. (array writing)
            //The calculated property name to be generated is consistent with the property name in state
            ...mapState(['sum', 'school', 'subject']),

            /* ******************************************************************** */

            /* bigSum(){
                return this.$store.getters.bigSum
            }, */

            //Generate calculation properties with mapGetters and read data from getters. (object writing)
            // ...mapGetters({bigSum:'bigSum'})

            //Generate calculation properties with mapGetters and read data from getters. (array writing)
            ...mapGetters(['bigSum'])

        },
        methods: {
            increment() {
                this.$store.commit('JIA', this.n)
            },
            decrement() {
                this.$store.commit('JIAN', this.n)
            },
            incrementOdd() {
                this.$store.dispatch('jiaOdd', this.n)
            },
            incrementWait() {
                this.$store.dispatch('jiaWait', this.n)
            },
        },
        mounted() {
            const x = mapState({he: 'sum', xuexiao: 'school', xueke: 'subject'})
            console.log(x)
        },
    }
</script>

<style lang="css">
    button {
        margin-left: 5px;
    }
</style>

Objects are written in the following ways:

...mapGetters({bigSum:'bigSum'})

  1. The extension operator (...) is used to take out all the traversable properties of the parameter object, and then copy them to the current object (the objects inside are expanded by attributes or values and placed in the outer object)
  2. The extension operator can convert [array] or [object] into a comma separated parameter sequence
  3. Deconstructed with extension operator

3. mapMutations and mapActions

3.1 basic usage

To use, first introduce the corresponding components

import {mapState, mapGetters} from 'vuex'
  1. mapActions method: the method used to help us generate a dialogue with actions, that is, $store Function of dispatch (xxx)

    methods:{
        //Generated by mapActions: incrementadd, incrementWait (object form)
        ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    
        //Generated by mapActions: incrementadd, incrementWait (array form)
        ...mapActions(['jiaOdd','jiaWait'])
    }
    
  2. mapMutations method: a method used to help us generate a conversation with mutations, that is, $store Function of commit (xxx)

    methods:{
        //Generated by mapActions: increment and decrement (object form)
        ...mapMutations({increment:'JIA',decrement:'JIAN'}),
        
        //Generated by mapMutations: JIA, JIAN (object form)
        ...mapMutations(['JIA','JIAN']),
    }
    

Note: when mapActions and mapMutations are used, if parameters need to be passed: pass the parameters when binding events in the template, otherwise the parameters are event objects.

3.2 example

src/store/index.js

And Src / store / index JS, slightly written here.

Count.vue

<template>
    <div>
        <h1>The current summation is:{{sum}}</h1>
        <h3>The current summation magnification is 10 times:{{bigSum}}</h3>
        <h3>I am here{{school}},study{{subject}}</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, //User selected number
            }
        },
        computed: {
            //Generate calculation properties with mapState and read data from state. (array writing)
            ...mapState(['sum', 'school', 'subject']),

            //Generate calculation properties with mapGetters and read data from getters. (array writing)
            ...mapGetters(['bigSum'])

        },
        
        /* ************************************************* */
        
        methods: {
            //The programmer writes the method himself
            /* increment(){
                this.$store.commit('JIA',this.n)
            },
            decrement(){
                this.$store.commit('JIAN',this.n)
            }, */

            //Generate the corresponding method with mapMutations, in which commit will be called to contact mutations (object writing method)
            ...mapMutations({increment: 'JIA', decrement: 'JIAN'}),

            //Generate the corresponding method with mapMutations, in which commit will be called to contact mutations (array writing method)
            // ...mapMutations(['JIA','JIAN']),
            
            /* ************************************************* */
            
            //The programmer writes the method himself
            /* incrementOdd(){
                this.$store.dispatch('jiaOdd',this.n)
            },
            incrementWait() {
                this.$store.dispatch('jiaWait',this.n)
            }, */

            //Generate corresponding methods with mapActions, in which dispatch will be called to contact actions (object writing method)
            ...mapActions({incrementOdd: 'jiaOdd', incrementWait: 'jiaWait'})

            //Generate the corresponding method with mapActions. In the method, dispatch will be called to contact actions (array writing method)
            // ...mapActions(['jiaOdd','jiaWait'])
        },
        mounted() {
            const x = mapState({he: 'sum', xuexiao: 'school', xueke: 'subject'})
            console.log(x)
        },
    }
</script>

<style lang="css">
    button {
        margin-left: 5px;
    }
</style>

4. Multi component data sharing

Case:

  • Sum and show sum to other components.
  • Add personnel and display the number of personnel in the personnel list to other components.

src/store/index.js

//This file is used to create the most core store in Vuex
import Vue from 'vue'
//Introduce Vuex
import Vuex from 'vuex'
//Apply Vuex plug-ins
Vue.use(Vuex);

//Prepare actions -- used to respond to actions in the component
const actions = {
    jiaOdd(context, value) {
        console.log('actions Medium jiaOdd Called');
        if (context.state.sum % 2) {
            context.commit('JIA', value)
        }
    },
    jiaWait(context, value) {
        console.log('actions Medium jiaWait Called');
        setTimeout(() => {
            context.commit('JIA', value)
        }, 500)
    }
}
//Prepare mutations -- for manipulating data (state)
const mutations = {
    JIA(state, value) {
        console.log('mutations Medium JIA Called');
        state.sum += value
    },
    JIAN(state, value) {
        console.log('mutations Medium JIAN Called');
        state.sum -= value
    },
    //Add a Person to the list
    ADD_PERSON(state, value) {
        console.log('mutations Medium ADD_PERSON Called');
        state.personList.unshift(value)
    }
}
//Prepare state -- used to store data
const state = {
    sum: 0, //Current and
    school: 'Hamapi',
    subject: 'back-end',
    personList: [
        {id: '001', name: 'Zhang San'}
    ]
};
//Prepare getters -- used to process the data in state
const getters = {
    bigSum(state) {
        return state.sum * 10
    }
};

//Create and expose store s
export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})

src/main.js

//Introduce Vue
import Vue from 'vue'
//Introduce App
import App from './App.vue'
//Introducing store
import store from './store'
//Turn off Vue's production prompt
Vue.config.productionTip = false;

//Create vm
new Vue({
	el:'#app',
	render: h => h(App),
	store
})

Count.vue

<template>
    <div>
        <h1>The current summation is:{{sum}}</h1>
        <h3>The current summation magnification is 10 times:{{bigSum}}</h3>
        <h3>I am here{{school}},study{{subject}}</h3>
        <h3 style="color:red">Person The total number of people in the assembly 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 corresponding components to generate corresponding calculation properties and functions
    import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'

    export default {
        name: 'Count',
        data() {
            return {
                n: 1, //User selected number
            }
        },
        computed: {
            //Generate calculation properties with mapState and read data from state. (array writing)
            ...mapState(['sum', 'school', 'subject', 'personList']),
            //Generate calculation properties with mapGetters and read data from getters. (array writing)
            ...mapGetters(['bigSum'])
        },
        methods: {
            //Generate the corresponding method with mapMutations, in which commit will be called to contact mutations (object writing method)
            ...mapMutations({increment: 'JIA', decrement: 'JIAN'}),
            //Generate corresponding methods with mapActions, in which dispatch will be called to contact actions (object writing method)
            ...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 The sum of components is:{{sum}}</h3>
        <input type="text" placeholder="Please enter your 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>

App.vue

<template>
    <div>
        <Count/>
        <hr>
        <Person/>
    </div>
</template>

<script>
    import Count from './components/Count'
    import Person from './components/Person'

    export default {
        name: 'App',
        components: {Count, Person},
        mounted() {
            // console.log('App',this)
        },
    }
</script>

5. Modularity + namespace (important)

5.1 basic use

  1. Purpose: to better maintain the code and make the classification of multiple data more clear.

    1. To put it bluntly, it is code separation and decoupling.
  2. Modify Src / store / index 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 the namespace is opened, read the state data from the component:

    //Method 1: read directly by yourself
    this.$store.state.personAbout.list
    //Method 2: read with mapState:
    ...mapState('countAbout',['sum','school','subject']),
    
  4. After the namespace is opened, the getters data is read from the component:

    //Method 1: read directly by yourself
    this.$store.getters['personAbout/firstPersonName']
    //Method 2: read with mapGetters:
    ...mapGetters('countAbout',['bigSum'])
    
  5. After namespace is opened, dispatch is invoked in the component.

    //Method 1: directly dispatch yourself
    this.$store.dispatch('personAbout/addPersonWang',person)
    //Method 2: with mapActions:
    ...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    
  6. After namespace is opened, commit is invoked in the component.

    //Method 1: commit yourself directly
    this.$store.commit('personAbout/ADD_PERSON',person)
    //Method 2: with mapMutations:
    ...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
    

5.2 example

5.2.1 code extraction

Steps:

  1. Set Src / store / index The code in JS is divided into multiple sets of configurations (multiple objects) according to business;
  2. Each set of configuration can include actions, variations, state and getters;
  3. Then further separate the code and put multiple sets of configurations in different js files;
  4. Finally, in Src / store / index JS through import.
src/store/count.js
//Summation related configuration
export default {
    namespaced: true, //After the namespace is opened, it corresponds to the key in the modules in the store to simplify the steps of reading state data in the component
    actions: {
        //sum is an odd number plus 1
        jiaOdd(context, value) {
            console.log('actions Medium jiaOdd Called')
            if (context.state.sum % 2) {
                context.commit('JIA', value)
            }
        },
        //Wait a minute and add 1
        jiaWait(context, value) {
            console.log('actions Medium jiaWait Called')
            setTimeout(() => {
                context.commit('JIA', value)
            }, 500)
        }
    },
    mutations: {
        //Add 1 directly
        JIA(state, value) {
            console.log('mutations Medium JIA Called')
            state.sum += value
        },
        //Direct minus 1
        JIAN(state, value) {
            console.log('mutations Medium JIAN Called')
            state.sum -= value
        },
    },
    //Store data
    state: {
        sum: 0, //Current and
        school: 'Hamapi',
        subject: 'back-end',
    },
    //Further processing of data is similar to the calculation attribute
    getters: {
        bigSum(state) {
            return state.sum * 10
        }
    },
}

remarks:

namespaced: true,

After the namespace is opened, it corresponds to the key in the modules in the store to simplify the steps of reading state data in the component.

src/store/person.js
//Personnel management related configuration
import axios from 'axios'
import {nanoid} from 'nanoid'

export default {
    namespaced: true, //Open namespace
    actions: {
        addPersonWang(context, value) {
            if (value.name.indexOf('king') === 0) {
                context.commit('ADD_PERSON', value)
            } else {
                alert('The added person must be surnamed Wang!')
            }
        },
        addPersonServer(context) {
            axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(
                response => {
                    context.commit('ADD_PERSON', {id: nanoid(), name: response.data})
                },
                error => {
                    alert(error.message)
                }
            )
        }
    },
    mutations: {
        //Add a Person to the list
        ADD_PERSON(state, value) {
            console.log('mutations Medium ADD_PERSON Called')
            state.personList.unshift(value)
        }
    },
    //Store data
    state: {
        personList: [
            {id: '001', name: 'Zhang San'}
        ]
    },
    //Further processing of data is similar to the calculation attribute
    getters: {
        firstPersonName(state) {
            return state.personList[0].name
        }
    },
}

remarks:

namespaced: true,

After the namespace is opened, it corresponds to the key in the modules in the store to simplify the steps of reading state data in the component.

src/store/index.js
//This file is used to create the most core store in Vuex
import Vue from 'vue'
//Introduce Vuex
import Vuex from 'vuex'
import countOptions from './count'
import personOptions from './person'
//Apply Vuex plug-ins
Vue.use(Vuex);

//Create and expose store s
export default new Vuex.Store({
    //Modular development
    modules: {
        countAbout: countOptions, //key : value
        personAbout: personOptions
    }
})

5.2.2 page preparation

Steps:

  1. Automatically generate or manually write corresponding calculation properties and corresponding functions,
  2. Automatically generated or manually written calculation properties and functions can be used on the page.
Count.vue

Mapstate, mapgetters, mapmutations and mapactions are used to automatically generate corresponding calculation attributes,

And automatic generation, calling the function of commit to contact movements, and calling dispatch to contact actions;

And adopt modular development.

<template>
    <div>
        <h1>The current summation is:{{sum}}</h1>
        <h3>The current summation magnification is 10 times:{{bigSum}}</h3>
        <h3>I am here{{school}},study{{subject}}</h3>
        <h3 style="color:red">Person The total number of people in the assembly 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 components
    import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'

    export default {
        name: 'Count',
        data() {
            return {
                n: 1, //User selected number
            }
        },
        computed: {
            //Generate calculation properties with mapState and read data from state. (array writing)
            ...mapState('countAbout', ['sum', 'school', 'subject']),
            ...mapState('personAbout', ['personList']),
            //Generate calculation properties with mapGetters and read data from getters. (array writing)
            ...mapGetters('countAbout', ['bigSum'])
        },
        methods: {
            //Generate the corresponding method with mapMutations, in which commit will be called to contact mutations (object writing method)
            ...mapMutations('countAbout', {increment: 'JIA', decrement: 'JIAN'}),
            //Generate corresponding methods with mapActions, in which dispatch will be called to contact actions (object writing method)
            ...mapActions('countAbout', {incrementOdd: 'jiaOdd', incrementWait: 'jiaWait'})
        },
        mounted() {
            console.log(this.$store)
        },
    }
</script>

<style lang="css">
    button {
        margin-left: 5px;
    }
</style>

remarks:

...mapState('countAbout', ['sum', 'school', 'subject']),

  1. Generate calculation properties with mapState and read data from state. (array writing)
  2. Automatically generate the calculation attribute of state data in countAbout configuration.

...mapMutations('countAbout', {increment: 'JIA', decrement: 'JIAN'}),

  • Generate the corresponding method with mapMutations, in which commit will be called to contact mutations (object writing method)
  • Automatically generate the corresponding function in the set of countAbout configuration, and commit in the function to contact changes.

Directly call the corresponding function or calculate the attribute on the page.

Person.vue

Manually write the calculation attribute corresponding to state and write it yourself,

Call commit to contact the functions of movements and dispatch to contact the functions of actions;

And adopt modular development.

<template>
    <div>
        <h1>Personnel list</h1>
        <h3 style="color:red">Count The sum of components is:{{sum}}</h3>
        <h3>The name of the first person on the list is:{{firstPersonName}}</h3>
        <input type="text" placeholder="Please enter your name" v-model="name">
        <button @click="add">add to</button>
        <button @click="addWang">Add a person surnamed Wang</button>
        <button @click="addPersonServer">Add a person with a random name</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.personAbout.personList
            },
            sum() {
                return this.$store.state.countAbout.sum
            },
            firstPersonName() {
                return this.$store.getters['personAbout/firstPersonName']
            }
        },
        methods: {
            add() {
                const personObj = {id: nanoid(), name: this.name}
                this.$store.commit('personAbout/ADD_PERSON', personObj)
                this.name = ''
            },
            addWang() {
                const personObj = {id: nanoid(), name: this.name}
                this.$store.dispatch('personAbout/addPersonWang', personObj)
                this.name = ''
            },
            addPersonServer() {
                this.$store.dispatch('personAbout/addPersonServer')
            }
        },
    }
</script>

remarks:

this.$store.getters['personAbout/firstPersonName']

  1. Call the function with the value of firstPersonName in getters in the configuration of personAbout;
  2. Call which function of getters in which set of configuration, separated by "/" in the middle, and wrapped with an array outside.

$store.commit('personAbout/ADD_PERSON', personObj)

  • Call personAbout. In the set of configurations, the name is add in mutations_ The parameter passed in the function of person is personObj;
  • Call which function of changes in which set of configuration, separated by "/", as the first parameter of commit, and the value passed to the function by the second parameter dimension of commit; And wrapped with ().

Directly call the corresponding function or calculate the attribute on the page.

Vue's content sorting is over here. Welcome to leave a message.

Keywords: Front-end Vue Vue.js

Added by jakeruston on Wed, 09 Mar 2022 08:46:13 +0200