当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vuex中的 mapState,mapGetters,mapActions,mapMutations 的使用

vuex中的 mapState,mapGetters,mapActions,mapMutations 的使用

2019年06月06日  | 移动技术网IT编程  | 我要评论

铁仕,喜宴酒,海洋房产

一、介绍 vuex里面的四大金刚:state, mutations,actions,getters

(上次记得关于vuex笔记 ,是一个简单的应用;这是一些简单的vue的小组件方法: )

何为四大金刚?

  1.state (这里可以是 小写的 state,跟官网保持一致,采用大写,因为个人习惯,后面的代码介绍采用小写)

  vuex的状态管理,需要依赖它的状态树,官网说:

  vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个“唯一数据源 (ssot)”而存在。这也意味着,每个应用将仅仅包含一个 store 实例。单一状态树让我们能够直接地定位任一特定的状态片段,在调试的过程中也能轻易地取得整个当前应用状态的快照。

  简单粗暴理解: 我们要把我们需要做状态管理的量放到这里来,然后在后面的操作动它

  我们来声明一个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

 我们有了state状态树,我们要改变它的状态(值),就必须用vue指定唯一方法 mutation,官网说:

 更改 vuex 的 store 中的状态的唯一方法是提交 mutation。vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。

 简单粗暴理解:任何不以mutation的方式改变state的值,都是耍流氓(违法)

   我们来一个mutation:

const mutation = {
 addviews (state) {
 state.views++
 },
 blogadd (state) {
 state.blognumber++
 },
 clicktotal (state) {
 state.total++
 }
} 

3.action

  action 的作用跟mutation的作用是一致的,它提交mutation,从而改变state,是改变state的一个增强版,官网说:

  action 类似于 mutation,不同在于:

action 提交的是 mutation,而不是直接变更状态。

action 可以包含任意异步操作。

  简单粗暴理解: 额,这总结的差不多了,就这样理解吧!

  我们来一个action:

const actions = {
 addviews ({commit}) {
 commit('addviews')
 },
 clicktotal ({commit}) {
 commit('clicktotal')
 },
 blogadd ({commit}) {
 commit('blogadd')
 }
}

4.getter

官网说:有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数。减少我们对这些状态数据的操作

简单粗暴理解:状态树上的数据比较复杂了,我们使用的时候要简化操作,上面的state.todos 是一个对象,在组件中挑不同的数据时,需要对其做下处理,这样每次需要一次就处理一次,我们简化操作,将其在getter中处理好,然后export 一个方法;(额,好像说复杂了)

 我们来一个getter:

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

二、使用

学不用,傻学,没啥用,我们得用起来:

 1、src 下新建文件

我们在项目(vue-cli 脚手架)下 src 文件夹下新建一个 store,在这个store下新建 index.js 文件,将上面的代码填入,如下面完整的内容:

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 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 }
})

请着重看加粗部分,非加粗部分是import 其他项目功能

3、组件中使用

先上这个组件代码:

<template>
 <div>
 <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>
 
 </div>
</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 

这些名字呢,是对应四大金刚的一个辅助函数,

a).mapstate,官网说: 

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

对于官网给出的例子,截个图,供学习,详情请进官网:  , 我记录下官网说的少的 ...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 挑出来, 返回的是一个数组
 }

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

总结:

mapstate, mapgetters, mapactions, mapmutations  就是简化我们的一些 this.$store.state.* 的操作,将this.$store.* 里面的状态 映射到我们辅助函数的属性值里面
方便我们在组件中调用。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网