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:'高領(lǐng)毛衣',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代碼中奈懒,使用變量時候郭赐,加一個()傳參調(diào)用即可實現(xiàn)
- 原來是 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 同樣 傳參寫法