[英]How to check whether a v-checkbox is selected in Vue JS?
I have a checkbox with the following events and props:我有一个包含以下事件和道具的复选框:
<v-checkbox
v-for="planets in allPlanets" :key="`planets_${planets.id}`"
:label="planets.name"
:value="planets.id"
v-model="selectedPlanets"
/>
Given that all of the checkboxes are brought in using a v-for, how can I check whether a checkbox is selected using a method or mounted function in Vue JS?鉴于所有复选框都是使用 v-for 引入的,我如何检查是否使用方法选择了复选框或在 Vue JS 中安装了 function?
For example:例如:
methods: {
checkSelected() {
????
},
Add a planets.selected key.添加一个 planets.selected 键。
allPlanets: [
{ name: 'Planet name', value: 'Planet value' , selected : false },
...,
...
],
}
And in your template:在您的模板中:
<v-checkbox
v-for="planets in allPlanets" :key="`planets_${planets.id}`"
:label="planets.name"
:value="planets.id"
v-model="planets.selected"
/>
Similar to:如同:
Display multiple checkbox in table format using <v-for> and <v-checkbox> in Vuetify? 在Vuetify中使用<v-for>和<v-checkbox>以表格格式显示多个复选框?
you have to make such a structure, so you know for each id, whether it is checked or not你必须做出这样的结构,所以你知道每个id,是否被检查
new Vue({
data: () => ({
allPlanets: [
{
id: 32,
name: "planent",
selected: false
},
{
id: 365,
name: "planet 2",
selected: false
}
],
}),
methods: {
checkSelectedByIndex(index) {
return this.allPlanets[index].selected
},
checkSelectedById(id) {
return this.allPlanets.find(p => p.id === id)?.selected ?? false
}
}
});
and in the you have to set the v-model="planets.selected"在你必须设置v-model="planets.selected"
Given your layout the simplest methods is:鉴于您的布局,最简单的方法是:
methods: {
checkSelected(id) {
return this.selectedPlanets.includes(id)
},
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.