Home >Web Front-end >JS Tutorial >Detailed explanation of the use of mapState and mapGetters in vuex

Detailed explanation of the use of mapState and mapGetters in vuex

php中世界最好的语言
php中世界最好的语言Original
2018-04-28 13:43:5241410browse

This time I will bring you a detailed explanation of the use of mapState and mapGetters in vuex. What are the precautions for using mapState and mapGetters in vuex. The following is a practical case, let's take a look.

1. Introduce the four kings in vuex: State, Mutations, Actions, Getters

(I remember the notes about vuex last time: http: //www.jb51.net/article/138229.htm, is a simple application; these are some simple vue widget methods: http://www.jb51.net/article/138230.htm)

What are the Four Diamonds?

1.State (this can be lowercase state, consistent with the official website, in uppercase, because of personal habits, the following code introduction is in lowercase)

The state management of vuex needs to rely on it The state tree, the official website says:

Vuex uses a single state tree - yes, one object contains all application-level states. It now exists as a "Single Source of Data (SSOT)". This also means that each application will only contain one store instance. A single state tree allows us to directly locate any specific piece of state and easily obtain a snapshot of the entire current application state during debugging.

Simple and rough understanding: We need to put the amount of state management we need here, and then move it in subsequent operations

Let’s declare a state:

const state = { 
 blogTitle: '迩伶贰blog',
 views: 10,
 blogNumber: 100,
 total: 0,
 todos: [
 {id: 1, done: true, text: '我是码农'},
 {id: 2, done: false, text: '我是码农202号'},
 {id: 3, done: true, text: '我是码农202号'}
 ]
}

2. Mutation

We have a state tree. If we want to change its state (value), we must use vue to specify the only method mutation. The official website says:

The only way to change the state in the Vuex store is to submit a mutation. Mutation in Vuex is very similar to events: each mutation has a string event type (type) and a callback function (handler).

Simple and rough understanding: Any change in the value of state without mutation is a rogue (illegal)

Let’s do a mutation:

const mutation = {
 addViews (state) {
 state.views++
 },
 blogAdd (state) {
 state.blogNumber++
 },
 clickTotal (state) {
 state.total++
 }
}

3. Action

The role of action is consistent with the role of mutation. It submits mutation and thereby changes state. It is an enhanced version of changing state. The official website says:

Action is similar to mutation , the difference is:

Action submits a mutation instead of directly changing the state.

Action can contain any asynchronous operation.

Simple and crude understanding: Well, that’s pretty much the summary, let’s understand it this way!

Let’s take an action:

const actions = {
 addViews ({commit}) {
 commit('addViews')
 },
 clickTotal ({commit}) {
 commit('clickTotal')
 },
 blogAdd ({commit}) {
 commit('blogAdd')
 }
}

4. Getter

The official website says: Sometimes we need to derive some states from the state in the store , such as filtering a list and counting. Reduce our operations on these state data

Simple and rough understanding: The data on the state tree is more complicated. When we use it, we need to simplify the operation. The state.todos above is an object. Choose different ones in the component. When receiving data, it needs to be processed, so that it needs to be processed once every time. We simplify the operation, process it in the getter, and then export a method; (well, it seems to be complicated)

Let’s get a getter:

const getters = {
 getToDo (state) {
 return state.todos.filter(item => item.done === true)
 // filter 迭代过滤器 将每个item的值 item.done == true 挑出来, 返回的是一个数组
 }
}

2. Use

It’s useless to learn, it’s useless, we have to use it:

1. Create a new file under src

We create a new store under the src folder under the project (vue-cli scaffolding), and create a new index.js file under this store. Fill in the above code, as shown below:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = { 
 blogTitle: '迩伶贰blog',
 views: 10,
 blogNumber: 100,
 total: 0,
 todos: [
 {id: 1, done: true, text: '我是码农'},
 {id: 2, done: false, text: '我是码农202号'},
 {id: 3, done: true, text: '我是码农202号'}
 ]
}
const actions = {
 addViews ({commit}) {
 commit('addViews')
 },
 clickTotal ({commit}) {
 commit('clickTotal')
 },
 blogAdd ({commit}) {
 commit('blogAdd')
 }
}
const mutations = {
 addViews (state) {
 state.views++
 },
 blogAdd (state) {
 state.blogNumber++
 },
 clickTotal (state) {
 state.total++
 }
}
const getters = {
 getToDo (state) {
 return state.todos.filter(item => item.done === true)
 // filter 迭代过滤器 将每个item的值 item.done == true 挑出来, 返回的是一个数组
 }
}
export default new Vuex.Store({
 state,
 actions,
 mutations,
 getters
})
// 将四大金刚挂载到 vuex的Store下

2, main.js import file

import Vue from 'vue'
import App from './App'
import router from './router/router.js'
// 引入 状态管理 vuex
import store from './store'
// 引入elementUI
import ElementUI from 'element-ui'
// 引入element的css
import 'element-ui/lib/theme-chalk/index.css'
// 引入font-awesome的css
import 'font-awesome/css/font-awesome.css'
// 引入自己的css
import './assets/css/custom-styles.css'
Vue.config.productionTip = false
Vue.use(ElementUI)
/* eslint-disable no-new */
new Vue({
 el: '#app',
 router,
 store,
 template: '<App/>',
 components: { App }
})

Please pay attention to the bold part, not the bold part Part of it is to import other project functions

3. Use

in the component. First enter the component code:

<template>
 <p>
 <h4>vuex的状态管理数据</h4>
 <h5>博客标题</h5>
 <i>
 {{this.$store.state.blogTitle}}
 </i>
 <h5>todos里面的信息</h5>
 <ul>
 <li v-for = "item in todosALise" :key="item.id">
 <span>{{item.text}}</span> <br>
 <span>{{item.done}}</span> 
 </li>
 </ul>
 <h5>初始化访问量</h5>
 <p>
 mapState方式 {{viewsCount}};<br>
 直接使用views {{this.$store.state.views}}
 </p>
 <h4>blogNumber数字 </h4>
 <span>state中blogNumber:{{this.$store.state.blogNumber}}</span>
 <h4>总计</h4>
 <span>state中total:{{this.$store.state.total}}</span>
 <p>
 <button @click="totalAlise">点击增加total</button>
 </p>
 
 </p>
</template>
<style>
</style>
<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex'
export default {
 data () {
 return {
 checked: true
 }
 },
 created () {
 // this.$store.dispatch('addViews') // 直接通过store的方法 触发action, 改变 views 的值
 this.blogAdd() // 通过mapActions 触发mutation 从而commit ,改变state的值
 },
 computed: {
 ...mapState({
 viewsCount: 'views'
 }),
 ...mapGetters({
 todosALise: 'getToDo' // getToDo 不是字符串,对应的是getter里面的一个方法名字 然后将这个方法名字重新取一个别名 todosALise
 })
 },
 methods: {
 ...mapMutations({
 totalAlise: 'clickTotal' // clickTotal 是mutation 里的方法,totalAlise是重新定义的一个别名方法,本组件直接调用这个方法
 }),
   ...mapActions({
 blogAdd: 'blogAdd' // 第一个blogAdd是定义的一个函数别名称,挂载在到this(vue)实例上,后面一个blogAdd 才是actions里面函数方法名称
 }) 
} } </script>

mapState, mapGetters, mapActions, mapMutations

These names are an auxiliary function corresponding to the four kings,

a).mapState, the official website says:

当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:

对于官网给出的例子,截个图,供学习,详情请进官网:https://vuex.vuejs.org/zh-cn/state.html  , 我记录下官网说的少的 ...mapState() 方法

vue 现在好多例子,都是用es6 写的,es6中增加了好多神兵利器,我们也得用用。我们也要用‘对象展开运算符',这个具体的用法,请参考具体的学习资料,我们主要讲讲 ...mapState({...}) 是什么鬼。

下面实例代码中:

html:

<p>
  mapState方式 {{viewsCount}};<br>
  直接使用views {{this.$store.state.views}}
</p>

js:

...mapState({
 viewsCount: 'views'
 }),

  我们需要使用一个工具函数将多个对象合并为一个,这个  ... 方法就合适了,将多个函数方法合并成一个对象,并且将vuex中的this.$store.views

映射到this.viewsCount (this -> vue)上面来,这样在多个状态时可以避免重复使用,而且当映射的值和state 的状态值是相等的时候,可以是直接使用 

...mapState({
 'views'
 }),

b).mapMutations 其实跟mapState 的作用是类似的,将组件中的 methods 映射为 store.commit 调用

上面的代码:

html:

<span>{{this.$store.state.total}}</span>
 <p>
 <button @click="totalAlise">点击增加total</button>
 </p>

js:

...mapMutations({
 totalAlise: 'clickTotal' // clickTotal 是mutation 里的方法,totalAlise是重新定义的一个别名方法,本组件直接调用这个方法
 })

c). mapActions, action的一个辅助函数,将组件的 methods 映射为 store.dispatch 调用

上例代码:

html:

<h4>blogNumber数字 </h4>
 <span>state中blogNumber:{{this.$store.state.blogNumber}}</span>

js:

方法调用:

created () {
 // this.$store.dispatch('blogAdd') // 直接通过store的方法 触发action, 改变 views 的值
 this.blogAdd() // 通过mapActions 触发mutation 从而commit ,改变state的值
 },

方法定义:

...mapActions({
blogAdd: 'blogAdd' // blogAdd是定义的一个函数别名称,挂载在到this(vue)实例上,blogAdd 才是actions里面函数方法名称 })

d). mapGetter 仅仅是将 store 中的 getter 映射到局部计算属性:

html:

<h5>todos里面的信息</h5>
 <ul>
 <li v-for = "item in todosALise" :key="item.id"> 
      // <li v-for = "item in this.$store.state.todos" :key="item.id"> 这里就是直接读取store的值,没有做过滤操作,如果需要过滤。
        还需要单独写方法操作
 <span>{{item.text}}</span> <br>
 <span>{{item.done}}</span> 
 </li>
 </ul>

 js:

...mapGetters({
 todosALise: 'getToDo' // getToDo 不是字符串,对应的是getter里面的一个方法名字 然后将这个方法名字重新取一个别名 todosALise
 }),

这个 getToDo 是在getters 定义的一个方法,它将todos 里的对象属性done为true的之过滤出来

getToDo (state) {
 return state.todos.filter(item => item.done === true)
 // filter 迭代过滤器 将每个item的值 item.done == true 挑出来, 返回的是一个数组
 }

上面代码操作后的效果截图:

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

vue常用组件使用详解

js实现复制文本文件功能(步奏详解)

The above is the detailed content of Detailed explanation of the use of mapState and mapGetters in vuex. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn