【发布时间】:2022-09-28 02:52:59
【问题描述】:
我有以下模板代码:
<script setup>
import {useProductStore} from \"@/store/products\";
import {ref} from \"vue\";
import {storeToRefs} from \"pinia\";
const productStore = useProductStore()
let { products } = storeToRefs(productStore)
let { categories } = storeToRefs(productStore)
const { showProducts } = productStore
</script>
<template>
<div>
<div class=\"row\">
<div class=\"col-md-2\">
<button class=\"d-block w-100\"
@click=\"showProducts(\'all\')\">All</button>
<button class=\"d-block w-100\"
@click=\"showProducts(category.id)\"
:key=\"category.id\"
v-for=\"category in categories\">{{ category.name }}</button>
</div>
<div class=\"col\">
<p v-for=\"product in showProducts(\'all\')\"
:key=\"product.id\">{{ product.name }}</p>
</div>
</div>
</div>
</template>
Pinia 商店的代码:
import { defineStore } from \'pinia\'
import axiosClient from \'@/axios\'
export const useProductStore = defineStore( \'products\', {
id : \'products\',
state: () => {
return {
products: [],
categories: [],
}
},
actions: {
async getProducts()
{
axiosClient.get(\'products\')
.then((response) => {
const data = response.data
this.products = data.products
this.categories = data.categories
})
}
},
getters: {
showProducts: (state) =>
{
return (categoryID) =>
{
if(categoryID === \'all\')
{
return state.products
}
return state.products.filter((product) => product.productCategoryID == categoryID)
}
}
},
})
初始数据已加载并显示,但单击事件未显示过滤数据(触发 showProducts 方法并过滤产品,但列表未在视觉上更改)。
我在这里做错了什么? 什么
-
您是否尝试过不破坏它?
const { showProducts } = productStore我猜它失去了反应性。试试productStore.showProducts -
这可能是由于 getter 与参数一起使用时的行为。 Documentation 声明,按照您的方式使用它们,getter 不再是 getter,而是一个简单调用的函数,这表明您必须在再次更改它们后调用它。