感謝您看我有點卡住了。試圖弄清楚如何在默認情況下選中第一個復選框。
這是我的 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>
uj5u.com熱心網友回復:
您可以在為模型設定資料時通過設定它來初始定義檢查的值:
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/
uj5u.com熱心網友回復:
(category, index) in categories
然后你可以設定選中狀態取決于 index == 0
uj5u.com熱心網友回復:
您應該在模型中設定真實來源,而不是在渲染中。
你應該有類似的東西
mounted() {
this.categories[0].id=true;
}
但是,尚不清楚類別的結構是什么。是陣列嗎?如果是這樣,您應該將其初始化為空陣列而不是物件。此外,如果您可能應該使用v-model而不是:value這樣,檢查狀態的更改將保存在模型中。最后,我不確定您是否希望將模型鏈接到id屬性。可能還有另一個要系結的屬性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/392444.html
標籤:javascript css Vuejs2 Vue 组件
