在Vue 2中,如何在v-for循环中只选中第一个输入类型复选框



谢谢你看我有点卡住了。试图弄清楚如何在默认情况下选中呈现的第一个复选框。

这是我的JS,类别正在动态中出现

Vue.component('category-filter', {
template: '#category-filter-template',
props: {
appMounted: false,
},
data() {
return {
categories: {},
checkedState: false,
};
},
methods: {
handleCheckboxClicked(e) {
console.log({ e });
},
},
mounted() {
this.appMounted = true;
this.categories =jsContext.categories
},
});

这是我的模板,我选择使样式内联,使组件更可重用

<div
class="filter-container--wrapper"
style="
display: -webkit-box;
display: -ms-flexbox;
display: flex;
flex-wrap: wrap;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
margin-bottom: 2rem;
color: #fff;
background-color: #5676a7;
border-radius: 5px;
"
>
<div
id="filter-item"
style="padding: 15px"
v-for="category in categories"
:key="category.id"
>
<input
id="category-name"
type="checkbox"
@click="handleCheckboxClicked($event)"
:value="category.id"
:checked="checkedState"
/>
<label for="category-name">
<span>{{category.name}}</span>
</label>
</div>
</div>

您可以在为模型设置数据时通过设置值来初始定义检查值:

this.categories = Array.from(jsContext.categories || []).map((v,i) => (v.checked = !i, v));

各种问题:

  • 您应该使用模型而不是:value,然后将模型更改为已检查
  • 不要改变道具
  • 如果类别是一个数组,则将其设置为数据中的数组,而不是对象
  • 内联样式最好使用计算道具,或者如果可能的话,总是把它放在CSS文件或<style>中,如果你不希望它冲突,你可以把它定为#category-filter-template .filter-container--wrapper {}
<template id="category-filter-template">
<div class="filter-container--wrapper" :style="wrapperStyle">
<div
id="filter-item"
:style="itemStyle"
v-for="category in categories"
:key="category.id"
>
<input
id="category-name"
type="checkbox"
v-model="category.checked"
:checked="category.checked"
/>
<label for="category-name">
<span>{{category.name}}</span>
</label>
</div>
</div>
</template>

然后你的组件:

Vue.component('category-filter', {
template: '#category-filter-template',
data() {
return {
categories: []
};
},
computed: {
wrapperStyle () {
return {
'display': 'flex',
'flex-wrap': 'wrap',
'-webkit-box-pack': 'center',
'-ms-flex-pack': 'center',
'justify-content': 'center',
'margin-bottom': ' 2rem',
'color': '#fff',
'background-color': ' #5676a7',
'border-radius': ' 5px'
}
},
itemStyle () {
return {
'padding': '15px'
}
}
},
mounted() {
this.categories = Array.from(jsContext.categories || []).map((v,i) => (v.checked = !i, v))
},
})

请参阅联机工作:https://playcode.io/847454/

您应该在模型中设置真相的来源,而不是在渲染中。

你应该有类似的东西

mounted() {
this.categories[0].id=true;
}

然而,目前还不清楚类别的结构是什么。它是一个数组吗?如果是这样,则应该将其初始化为空数组,而不是对象。此外,如果您可能应该使用v-model而不是:value,以便将检查状态的更改保存在模型中。最后,我不确定您是否希望将模型链接到id属性。可能还有另一个属性需要绑定。

相关内容

最新更新