美文网首页
vuex中的 mapGetters 传参写法

vuex中的 mapGetters 传参写法

作者: 糖小羊儿 | 来源:发表于2021-02-05 13:08 被阅读0次

store.js代码

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cart:[
      {id:1,name:'2021时尚连衣裙',price:182},
      {id:2,name:'高领毛衣',price:35},
      {id:3,name:'羽绒服外套',price:267},
      {id:4,name:'运动老爹鞋',price:215},
      {id:5,name:'毛呢大衣',price:121},
      {id:6,name:'半身裙A字裙',price:99.1},
      {id:7,name:'保暖套装',price:78.4},
      {id:8,name:'袜子',price:56},
      {id:9,name:'帽子',price:321},
      {id:10,name:'手套',price:56},
    ],
  },
  getters:{
    cartList(state){
      return (keyword)=>{
        if(keyword){
          let result= state.cart.filter((item)=>{
            return item.name.includes(keyword);
          })
          return result;
        }else{
          return state.cart;
        }
      }
    },

  },
  
})

组件中代码

mapGetters还是普通的写法,就只需要在html代码中,使用变量时候,加一个()传参调用即可实现

  • 原来是 v-for="(item, index) in cartList"
  • 改为 v-for="(item, index) in cartList(keyword)"
<template>
  <div class="home">
    <input type="text" v-model="keyword" />
    <ul>
      <li v-for="(item, index) in cartList(keyword)" :key="index">
        <span>{{ item.name }}</span>
        <span>¥{{ item.price }}</span>
      </li>
    </ul>
  </div>
</template>
import { mapGetters } from "vuex";
export default {
  name: "Home",
  data() {
    return {
      keyword: "",
    };
  },
  computed: {
    ...mapGetters({
      cartList: "cartList",
    }),
  },
};
  • 注意:vuex中的 mapMutations 同样 传参写法

相关文章

网友评论

      本文标题:vuex中的 mapGetters 传参写法

      本文链接:https://www.haomeiwen.com/subject/jtgwtltx.html