提问人:Andy 提问时间:11/16/2023 最后编辑:Boussadjra BrahimAndy 更新时间:11/16/2023 访问量:19
VueJS 将参数传递给绑定属性
VueJS passing parameter to bound property
问:
我想跟踪多个按钮的状态,而每个按钮都没有跟踪器变量和函数。
因此,我想将参数传递给计算属性,如下所示:
<div class="grid grid-cols-5 text-sm my-3">
<div @click="toggleShow('weapon')" :class="showStyle('weapon')">Weapon</div>
<div @click="toggleShow('armor')" :class="showStyle('armor')">Armor</div>
<div @click="toggleShow('ring')" :class="showStyle('ring')">Ring</div>
<div @click="toggleShow('amulet')" :class="showStyle('amulet')">Amulet</div>
<div @click="toggleShow('horse')" :class="showStyle('horse')">Horse</div>
</div>
但是,这两种方法都不起作用:
const showStyle = (category: string) =>
computed(() => {
if (show.value.get(category)) {
return "bg-green-700";
} else {
return "bg-red-700";
}
});
// I am not redeclaring in my real code, this is just in the same block for demonstration
// gives error $setup.showStyle is not a function
const showStyle = computed((category) => {
if (show.value.get(category)) {
return "bg-green-700";
} else {
return "bg-red-700";
}
});
我正在使用地图来跟踪每个标志:
const show = ref(new Map());
show.value.set("weapon", true);
show.value.set("armor", true);
show.value.set("ring", true);
show.value.set("amulet", true);
show.value.set("horse", true);
show.value.set("potion", false);
切换函数似乎在交换值时起作用:
function toggleShow(category: string) {
alert(show.value.get(category));
show.value.set(category, !show.value.get(category));
}
我想避免的是为每个类别设置一个单独的值,而是传入参数。computed()
这可能吗?如何?
答:
3赞
Boussadjra Brahim
11/16/2023
#1
您可以通过从计算属性返回一个函数来参数化计算属性,如下所示:
const showStyle = computed(()=> (category) => {
if (show.value.get(category)) {
return "bg-green-700";
} else {
return "bg-red-700";
}
});
这工作正常,但它没有比标准函数额外的好处:
const showStyle = (category) => {
if (show.value.get(category)) {
return "bg-green-700";
} else {
return "bg-red-700";
}
}
您可以从 Estus Flask 查看此答案以获得更多解释。
评论