03.vuex 中 getter

index.js

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

Vue.use(Vuex)

export default new Vuex.Store({
  // data
  state: {
    count: 0,
    msg: 'hello world',
    num: 11,
    val: 12
  },
  // methods
  mutations: {
    addNum(state) {
      state.count++
    },
    setNum(state, val) {
      state.num = val
    }
  },
  // 异步方法
  actions: {
    
  },
  // 模块
  modules: {
  },
  // 相当于 computed getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
  getters: {
    reverseMsg: function (state) {
      return state.msg.split('').reverse().join('')
    },
    mixinMsg: function (state) {
      return function (val) {
        return state.msg + val
      }
    }
  }
})

get.vue

<template>
  <div>
    <h1>
      {{$store.getters.reverseMsg}}
    </h1>
    <h2>{{}}</h2>
    <h2>{{msg}}</h2>
    <h2>{{num}}</h2>
    <h2>{{mixinMsg1}}</h2>
  </div>
</template>

<script>
  import { mapGetters, mapState } from 'vuex'
  // 引入 getter state
  let mapGetData = mapGetters(['reverseMsg', 'mixinMsg'])
  let mapStateData = mapState(['msg', 'num', 'val'])
  export default {
    name: "get",
    // computed: {
    //   reverseMsg: function () {
    //     return this.$store.getters.reverseMsg
    //   }
    // },

    // 解构
    // computed: {
    //   ...mapGetData,
    //   ...mapStateData
    // },

    // getter 返回一个函数,来实现给 getter 传参。在你对 store 里的数组进行查询时非常有用。
    computed: {
      mixinMsg1: function () {
        return this.$store.getters.mixinMsg('123456')
      },
      ...mapStateData,
      ...mapGetData
    },



    mounted() {
      console.log(this)
    }
  }
</script>

<style scoped>

</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值