vuejs가 있는 하위 구성 요소에서 확인란 선택/선택 해제
콘텍스트:
VueJs를 프로젝트에서 처음 사용하기 때문에 제대로 사용하지 못할 수 있습니다.
부모 컴포넌트와 자녀 컴포넌트가 있습니다.
부모 : Research Products.vue : 카테고리별로 필터링할 수 있는 제품 목록을 표시합니다.필터는 제품의 카테고리와 관련된 체크 박스입니다.
아이 : Category Display (카테고리 디스플레이vue : 카테고리 행의 뷰와 메서드를 처리하는 컴포넌트입니다.
질문 내용:
자식 구성 요소 내에서 범주 확인란을 클릭하고 이 확인란을 선택하면 범주가 상위 구성 요소의 필터 목록에 추가됩니다.이거 되는구나.
체크박스를 끄면 카테고리가 이 목록에서 삭제됩니다.이것도 돼요.
사용자가 필터를 더 쉽게 볼 수 있도록 모든 카테고리를 상위 구성 요소에서 버튼으로 표시했습니다.또한 자 컴포넌트를 클릭했을 때 이 버튼을 클릭하면 해당 체크박스가 꺼집니다.
실제 코드는 다음과 같습니다.
리서치 프로덕트vue:
<template>
<div>
<template v-for="category in categories">
<category-display
:category="category"
:key="'category_'+category.id"
:checked="checked"
@categorySelected="categorySelected"
></category-display>
</template>
<button
v-for="filter in listFilters"
:key="'filter_'+filter.slug"
class="btn btn-light btn-sm mr-2 mb-2"
@click="removeFilter(filter)"
>
{{ filter.name }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
categories: { // HERE A COLLECTION CONTAINING ALL MY CATEGORIES },
selectedCategories: [],
listFilters: []
};
},
methods: {
categorySelected(category) {
var newCategory = {
type: "category",
slug: category.slug,
name: category.name
};
if (category.checked) {
if (!this.selectedCategories.includes(category.slug)) {
this.selectedCategories.push(category.slug);
this.listFilters.push(newCategory);
}
} else {
if (this.selectedCategories.includes(category.slug)) {
const index = this.selectedCategories.indexOf(category.slug);
if (index > -1) {
this.selectedCategories.splice(index, 1);
}
}
this.listFilters = this.listFilters.filter(function(item) {
for (var key in newCategory) {
if (item[key] === undefined || item[key] == newCategory[key])
return false;
}
return true;
});
}
},
removeFilter(filter) {
// THERE, I NEED TO UNCHECK THE RELATED CHECKBOX IN CHILD COMPONENT
this.listFilters = this.listFilters.filter(function(item) {
for (var key in filter) {
if (item[key] === undefined || item[key] == filter[key]) return false;
}
return true;
});
}
}
};
</script>
카테고리 디스플레이vue:
<template>
<b-form-checkbox-group class="w-100">
<b-form-checkbox :value="category.slug" class="w-100" @input="selection" v-model="selected" ref="checked">
{{ category.name }}
<span class="badge badge-secondary float-right">{{ category.products_count }}</span>
</b-form-checkbox>
</b-form-checkbox-group>
</template>
<script>
export default {
props: {
category: {
type: Object,
required: true
}
},
data() {
return {
selected: false
}
},
methods: {
selection() {
var response = false;
if(this.selected.length !== 0){
response = true;
}
this.$emit('categorySelected', {slug: this.category.slug, name: this.category.name, checked: response});
}
}
};
</script>
여기 참고용으로 간단한 샘플이 있습니다.를 사용할 수 있습니다.sync부모 및 자녀 간의 양방향 바인딩을 실현하기 위한 수식자.그리고 아이의 계산된 속성과 함께setter그리고.getter
따라서 모든 범주를 하위 항목으로 전달하고 선택한 범주를 동기화합니다.
<HelloWorld :cats.sync="selectedCategories" :categories="categories"/>
하위 구성 요소는 범주를 사용하고 반복하며 확인란을 표시합니다.여기서는 계산된 속성을 사용합니다.체크박스를 켜면setter는 변경을 부모에게 송신합니다.
<label v-for="c in categories" :key="c.id">
<input v-model="temp" type="checkbox" :value="c">
{{ c.name }}
</label>
스크립트:
computed: {
temp: {
get: function() {
return this.cats;
},
set: function(newValue) {
this.$emit("update:cats", newValue);
}
}
}
그리고 부모는 그저 반복할 뿐입니다selectedCategories그리고 당신이 원하는 대로, 부모에게 변화가 생겼을 때selectedCategories아이템이 삭제되면 자녀는 자동으로 인식됩니다.
여기 전체 샘플이 있습니다.SANDBOX
언급URL : https://stackoverflow.com/questions/62429355/check-uncheck-a-checkbox-in-a-child-component-with-vuejs
'source' 카테고리의 다른 글
| MySQLdb, mysqlclient 및 MySQL 커넥터/Python의 차이점은 무엇입니까? (0) | 2022.11.22 |
|---|---|
| vue 라우터를 사용하여 모델 제어 (0) | 2022.11.22 |
| if 조건으로 MySQL 업데이트 (0) | 2022.11.22 |
| 인덱스(0 기준)는 0보다 크거나 같아야 합니다. (0) | 2022.11.22 |
| .NET Entity Framework 버전이 다르므로 코어 빌드 경고 (0) | 2022.11.22 |