Lesson 5 vuex after reading this, you will

Time:2021-3-3

Like Vue router, vuex is the core plug-in of Vue. It is the state management of Vue. For the value transfer between cross components, these values can be put into the state state for management

1. State usage

In Lecture 2, I have modified the Src / store folder. Here, I will start with Src / store/ state.js Add a new value in, and then explain the usage of vuex


const state = {

 menuType: 1

}

export default state

And that willmenuTypePut it in vuex and let vuex manage this value. Next, demonstrate the value called in the component:


<template>

 <section>

 {{menuType}}

 </section>

</template>

<script>

export default {

 computed: {

 menuType () {

 return this.$store.state.menuType

 }

 },

 data () {

 return {

 }

 },

 methods: {

 },

}

</script>

How to get the value in the module?

Let’s take a look at the new Src / store / module I created in lesson 2/ user.js File, which is a module if in user.js How to get a new value in the component?

const state = {

 User name: 'Zhang San'

}

const getters = {}

const mutations = {}

const actions = {}

export default {

 state,

 getters,

 mutations,

 actions

}

Call this value in the component

<template>

 <section>

 {{menuType}}

 {{userName}}

 </section>

</template>

<script>

export default {

 computed: {

 menuType () {

 return this.$store.state.menuType

 },

 userName () {

 return this.$ store.state.user . username // calls the value in the module

 }

 },

 data () {

 return {

 }

 },

 methods: {

 },

}

</script>

In addition to the way to get values in the components mentioned above, you can also use the auxiliary functions provided by vuexmapSateTo get the value:


<template>

 <section>

 {{menuType}}

 {{userName}}

 </section>

</template>

<script>

import {mapState} from 'vuex'

export default {

 computed: {

 ...mapState({

 menuType: state => state.menuType,

 userName: state => state.user.userName

 })

 },

 data () {

 return {

 }

 },

 methods: {

 },

}

</script>

It can also be abbreviated as follows:

computed: {

 ...mapState({

 menuType: state => state.menuType,

 userName: state => state.user.userName

 })

 },

 //Written by Jane

 computed: {

 ...mapState({

 userName: state => state.user.userName

 }),

 ...mapState([

 'menuType',

 ]),

 },

2. Getter usage

It is equivalent to the computed attribute in Vue, such as menutype = 1. In my own project, it represents the menu type, 1 represents Ping dial test menu, and 2 represents web page dial test menu. When getting this value in the component, it is meaningless to repeatedly judge, so we can put it in the getter to judge

Find Src / store/ getter.js :

const getters = {

 menuType: state => {

 if (state.menuType == 1) {

 Return 'Ping test'

 } else {

 Return 'webpage dial test'

 }

 }

}

export default getters

Then get the value in the component


<template>

 <section>

 {{menuTypeName}}

 </section>

</template>

<script>

export default {

 computed: {

 menuTypeName () {

 return this.$store.getters.menuType

 }

 },

 data () {

 return {

 }

 },

 methods: {

 },

}

</script>

You can also use the auxiliary functions provided by vuexmapGettersTo get the value:


computed: {

 ...mapGetters([

 'menuType'

 ])

 },

How to get the getters written in the module?

We are in Src / store / module/ user.js Add the following code:

const state = {

 User name: 'Zhang San'

}

const getters = {

 userName: state => {

 return  state.userName  +'is the administrator'

 }

}

const mutations = {}

const actions = {}

export default {

 state,

 getters,

 mutations,

 actions

}

Using auxiliary function of vuexmapGettersTo get the getters written in the module:


<template>

 <section>

 {{userName}}

 </section>

</template>

<script>

import {mapState, mapGetters} from 'vuex'

export default {

 computed: {

 // menuTypeName () {

 //     return this.$store.getters.menuType

 // },

 ...mapGetters([

 'userName'

 ])

 },

 data () {

 return {

 }

 },

 methods: {

 },

}

</script>

3. Usage of mutation

The previous two sections mainly talk about how to obtain the value in vuex. If you want to modify the value in vuex, you need to submit a mutation through commit to modify it

Find Src / store/ mutations.js File, add the following code:


const mutations = {

 SET_MENU_TYPE (state, params) {

 state.menuType = params

 }

}

export default mutations

Then call the mutation in the component:

<template>

 <section>

 <p>{{menuType}}</p>

 < button @ Click = "handlechangemenutype ('2 ')" > modify the value of menutype < / button >

 </section>

</template>

<script>

import {mapState} from 'vuex'

export default {

 computed: {

 ...mapState([

 'menuType',

 ]),

 },

 data () {

 return {

 }

 },

 methods: {

 handleChangeMenuType (params) {

 this.$store.commit('SET_MENU_TYPE', params)

 }

 },

}

</script>

Similarly, vuex also provides auxiliary functionsmapMutationsTo quickly set the value:

<template>

 <section>

 <p>{{menuType}}</p>

 < button @ Click = "handlechangemenutype ('2 ')" > modify the value of menutype < / button >

 </section>

</template>

<script>

import {mapState, mapMutations} from 'vuex'

export default {

 computed: {

 ...mapState([

 'menuType',

 ]),

 },

 data () {

 return {

 }

 },

 methods: {

 ...mapMutations([

 'SET_MENU_TYPE'

 ]),

 handleChangeMenuType () {

 this.SET_MENU_TYPE('2')

 }

 },

}

</script>

Or the same problem, how to submit the mutation for the values in the module? Let me give you an example

Or in Src / store / module/ user.js Add the following code:

const state = {

 User name: 'Zhang San'

}

const getters = {

 userName: state => {

 return  state.userName  +'is the administrator'

 }

}

const mutations = {

 SET_USER_NAME (state, params) {

 state.userName = params

 }

}

const actions = {}

export default {

 state,

 getters,

 mutations,

 actions

}

Then call the mutation written in the module in the component:

<template>

 <section>

 {{taskId}}

 <ul>

 <li>Did you take your medicine today? </li>

 </ul>

 <p>{{userName}}</p>

 < button @ Click = "handlechangemenutype" > modify the value of menutype < / button >

 </section>

</template>

<script>

import {mapState, mapGetters, mapMutations} from 'vuex'

export default {

 computed: {

 ...mapGetters([

 'userName'

 ])

 },

 data () {

 return {

 }

 },

 methods: {

 ...mapMutations([

 'SET_USER_NAME'

 ]),

 handleChangeMenuType () {

 this.SET_ USER_ Name ('li Si ')

 }

 },

}

</script>

4. Action usage

The above-mentioned call mutation to modify the value in vuex. This process is a synchronous operation. If a value needs asynchronous operation to be modified successfully, you need to call action. It is dedicated to processing asynchronous requests and then changing the value in vuex

For example, the navigation menu in a project needs to be dynamically returned by the back end. Operations such as requesting data must be asynchronous. At this time, I will simulate a request to modify itmenuListThis value


const state = {

 menuType: 1,

 menuList: []

}

export default state

First, in Src / store/ mutations.js Create a new mutation in the


const mutations = {

 SET_MENU_TYPE (state, params) {

 state.menuType = params

 },

 SET_MENU_LIST (state, params) {

 state.menuList = params

 }

}

export default mutations

Secondly, create a new Src / API/ app.js File, which simulates an asynchronous request interface:

export const getMenuList = () => {

 return new Promise((resolve, reject) => {

 const err = null

 setTimeout(() => {

 if (!err) {

 resolve({

 code: 200,

 data: {

 menuList: [

 {Name: 'create task'},

 {Name: 'task list'}

 ]

 }

 })

 } else {

 reject(err)

 }

 })

 })

}

Find Src / store/ actions.js File, add the following code:


import {getMenuList} from '@/api/app'

const actions = {

 updateMenuList ({commit}) {

 getMenuList().then(res => {

 const {code, data: {menuList}} = res

 commit('SET_MENU_LIST', menuList)

 }).catch(err => {

 console.log(err)

 })

 }

}

export default actions

Digression: when calling an asynchronous function and receiving the returned value, you can use the async / await function of ES7, which is written as follows:


import {getMenuList} from '@/api/app'

const actions = {

 async updateMenuList({commit}) {

 try {

 const {code, data: {menuList}} = await getMenuList()

 commit('SET_MENU_LIST', menuList)

 } catch (err) {

 console.log(err)

 }

 }

}

export default actions

Then call the action in the component:

<template>

 <section>

 < button @ Click = "handlechangemenulist" > get menu list asynchronously < / button >

 <ul>

 <li v-for="(item, index) in menuList" :key="index">{{item.name}}</li>

 </ul>

 </section>

</template>

<script>

import {mapState, mapGetters, mapMutations} from 'vuex'

export default {

 computed: {

 ...mapState([

 'menuList',

 ]),

 },

 data () {

 return {

 }

 },

 methods: {

 handleChangeMenuList () {

 this.$store.dispatch('updateMenuList')

 }

 },

}

</script>

Similarly, vuex also provides auxiliary functionsmapActionsTo call action:

<template>

 <section>

 < button @ Click = "handlechangemenulist" > get menu list asynchronously < / button >

 <ul>

 <li v-for="(item, index) in menuList" :key="index">{{item.name}}</li>

 </ul>

 </section>

</template>

<script>

import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'

export default {

 computed: {

 ...mapState([

 'menuList',

 ]),

 },

 data () {

 return {

 }

 },

 methods: {

 ...mapActions([

 'updateMenuList'

 ]),

 handleChangeMenuList () {

 this.updateMenuList()

 }

 },

}

</script>

Or the same problem, how to call the action written in the module?

Find Src / API/ app.js File, add an asynchronous interface:

export const getUserName = () => {

 return new Promise((resolve, reject) => {

 const err = null

 setTimeout(() => {

 if (!err) {

 resolve({

 code: 200,

 data: {

 Name: 'Li Si'

 }

 })

 } else {

 reject(err)

 }

 })

 })

}

Then in Src / store / module/ user.js Add a new method to actions in the file:

import {getUserName} from '@/api/app'

const state = {

 User name: 'Zhang San'

}

const getters = {

 userName: state => {

 return  state.userName  +'is the administrator'

 }

}

const mutations = {

 SET_USER_NAME (state, params) {

 state.userName = params

 }

}

const actions = {

 async getUserName ({commit}) {

 try {

 const {code, data: {name}} = await getUserName()

 commit('SET_USER_NAME', name)

 } catch (error) {

 console.log(err)

 }

 }

}

export default {

 state,

 getters,

 mutations,

 actions

}

Finally, call in the component:

<template>

 <section>

 < button @ Click = "handlechangemenulist" > get menu list asynchronously < / button >

 <ul>

 <li v-for="(item, index) in menuList" :key="index">{{item.name}}</li>

 </ul>

 < button @ Click = "handlechangeuser" > get user name asynchronously < / button >

 <p>{{userName}}</p>

 </section>

</template>

<script>

import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'

export default {

 computed: {

 ...mapState([

 'menuList',

 ]),

 ...mapGetters([

 'userName'

 ])

 },

 data () {

 return {

 }

 },

 methods: {

 ...mapMutations([

 'SET_USER_NAME'

 ]),

 ...mapActions([

 'updateMenuList',

 'getUserName'

 ]),

 handleChangeMenuList () {

 this.updateMenuList()

 },

 handleChangeUserName () {

 this.getUserName()

 }

 },

}

</script>

The above is the basic usage of vuex. Through this article, I believe that there is no problem in using vuex in projects. For more advanced usage of vuex, you can learn it in the next article

Recommended Today

Third party calls wechat payment interface

Step one: preparation 1. Wechat payment interface can only be called if the developer qualification has been authenticated on wechat open platform, so the first thing is to authenticate. It’s very simple, but wechat will charge 300 yuan for audit 2. Set payment directory Login wechat payment merchant platform( pay.weixin.qq . com) — > Product […]