07Vue3-Vuex中计算数学getters应用

17 篇文章 5 订阅

getters

Home.vue

<template>
  <div class="home">
    <h2>这是在单页模板中应用</h2>
    <h3>count:{{count}}</h3>
    <h3>计算属性:{{mypow}}</h3>
    <button @click="count--">-</button>
    <button @click="count++">+</button>
    <hr>
    <h2>使用全局的状态管理</h2>
    <h3>Num:{{$store.state.num}}</h3>
    <h3>state中的平方{{vuexpow}}</h3>
    <h3>使用getter中的计算属性:{{$store.getters.vxnumpow}}</h3>
    <button @click="$store.state.num--">-</button>
    <button @click="$store.state.num++">+</button> 
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'Home',
  components: {
    HelloWorld
  },
  data() {
    return {
      count: 2
    }
  },
  computed: {
    mypow() {
      return this.count*this.count
    },
    vuexpow() {
      return this.$store.state.num * this.$store.state.num
    }
  }
}
</script>

index.js

import { createStore } from 'vuex'

export default createStore({
  state: {
    //任何地方都可使用这个状态管理
    num: 2,
    mnum: 0,
    cartlist: [
      {name: '1',price: 24},
      {name: '2',price: 12},
      {name: '3',price: 42},
      {name: '4',price: 55},
    ]
  },
  getters: {
    //第一个参数就是state
    vxnumpow(state) {
        return state.num * state.num;
    },
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

效果
在这里插入图片描述
getters里的计算属性可复用
Home.vue

<h3>购物车的总价:{{$store.getters.totalprice}}</h3>
<h3>购物车的数量:{{$store.getters.goodsnum}}</h3>

index.js

getters: {
    //第一个参数就是state
    vxnumpow(state) {
        return state.num * state.num;
    },
    // totalprice(state) {
    //   return state.cartlist.reduce((s,n)=>s+n.price, 0)
    // },
    goodsnum(state) {
      return state.cartlist.filter(n => n.price >30);
    },
    //复用计算属性,传getters属性
    totalprice(state,getters) {
      return getters.goodsnum.reduce((s,n)=>s+n.price, 0)
    },
  },

效果
在这里插入图片描述
getters若是不是固定的某个参数,想要自己传参呢,可采用下面的方式
Home.vue

<!--    自定义传参-->
    <h3>购物车的数量:{{$store.getters.goodsself(20)}}</h3>

index.js

getters: {
    goodsself(state, getters) {
      // return function (price) {
      //   return state.cartlist.filter(n => n.price >price);
      // }
      //等价于
      return price => state.cartlist.filter(n => n.price >price);
    },
  },

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值