vuex getters计算过滤操作

vuex的Getters特性(store的计算属性,多组件复用)

  • getters可以对state进行计算操作,它就是store的计算属性
  • 虽然在组件内也可以做计算属性,但是getters可以在多组件之间复用
  • 如果一个状态只在一个组件内使用,是可以不用getters

getters从表面是获得的意思,可以把他看作在获取数据之前进行的一种再编辑,相当于对数据的一个过滤和加工。可以把它看作store.js的计算属性。

 getters基本用法

比如我们现在要对store.js文件中的count进行一个计算属性的操作,就是在它输出前,给它加上100.

我们首先要在store.js里用const声明我们的getters属性。

// 3、getters计算过滤操作
const getters = {
  // count: (state) => {
  //   state.count += 100
  // }
  count (state) {
    const gettersCount = state.count += 100
    return gettersCount 
  }
}

其中module模块组中要加上getters

// module模块组

const moduleA = {

  state,

  mutations,

  getters

}

export default new Vuex.Store({
  modules: { a: moduleA }
})

store.js里的配置算是完成了,需要到模板页对computed进行配置。在vue 的构造器里边只能有一个computed属性,如果你写多个,只有最后一个computed属性可用,所以要对computed属性进行一个改造,改造时我们使用ES6中的展开运算符”…”。

computed:{
    ...mapState(["count"]),
    count(){
        return this.$store.getters.count;
    }
},

这样的话,在每次count 的值发生变化的时候,都会进行加100的操作。

另外getters还有一种简化写法:用mapGetters简化

用mapGetters简化模板写法

(1)首先用import引入我们的mapGetters

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

(2)在computed属性中加入mapGetters

...mapGetters(["count"])

完整代码:

Count.vue

<template>
    <div>
        <h2>{{msg}}</h2>
        <hr/>
        <h3>{{$store.state.a.count}} = {{count}}</h3>
        <div>
            <button @click="$store.commit('add',10)">+</button>
            <button @click="$store.commit('reduce')">-</button>
        </div>
        <div>
          <p>
            <button @click="add(10)">add</button>
            <button @click="reduce">reduce</button>
          </p>
        </div>
    </div>
</template>
<script>
import store from '../store'
import {
  mapMutations,
  mapGetters,
  mapActions
} from 'vuex'

export default{
  data () {
    return {
      msg: 'Hello Vuex'
    }
  },
  computed: {
    // ...mapState(["count"]),
    count () {
      return this.$store.state.a.count
    },
    ...mapGetters(['count'])
  },
  store
}
</script>

store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// state访问状态对象
const state = {
  count: 1
}

// mutations修改状态
const mutations = {
  add (state, n) {
    state.count += n
  },
  reduce (state) {
    state.count--
  }
}

// getters计算过滤操作
const getters = {
  // count: (state) => {
  //   state.count += 100
  // }
  count (state) {
    state.count += 100
  }
}

// module模块组
const moduleA = {
  state,
  mutations,
  getters,
  actions
}


export default new Vuex.Store({
  // state,
  // mutations,
  // getters
module: { a: moduleA }
})

在每次count 的值发生变化的时候,都会进行加100的操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值