const state = reactive({
rows : [],
brandRows : [],
sort : 1,
categoryList : [],
genderList : [],
brandIdList : [],
inventoryDivList : [],
sizeList : [],
wishPriceList : []
})
const isChecked = (brandId) => {
return state.brandIdList.includes(brandId);
}
const toggleBrandId = (brandId) => {
const index = state.brandIdList.indexOf(brandId);
if (index !== -1) {
state.brandIdList.splice(index, 1);
} else {
state.brandIdList.push(brandId);
}
}
watch([() => state.categoryList, () => state.genderList, () => state.brandIdList], () => {
handleData();
});
문제)
state.categoryList, state.genderList값이 변할때는 즉각 데이터를 읽어오는데 state.brandIdList값이 변할때는 데이터를 읽어오지 못함
해결)
watch() 함수가 작동하지 않는 이유는 state.brandIdList 값을 직접 수정하지 않고 toggleBrandId() 함수를 통해 값을 변경하고 있기 때문
Vue의 반응형 시스템은 배열의 메서드 중 일부(예: push(), pop(), splice() 등)를 감지할 수 없으므로, Vue는 state.brandIdList 배열의 변경을 감지하지 못함
따라서 toggleBrandId() 함수에서 state.brandIdList 배열의 값을 직접 변경하는 대신, 새로운 배열을 생성하고 이를 state.brandIdList에 할당하면 state.brandIdList 배열의 변경을 감지할 수 있게 된다.. 그런데 너무 비효율적인것 아닌지..
const toggleBrandId = (brandId) => {
const index = state.brandIdList.indexOf(brandId);
const newArray = [...state.brandIdList]; // 새로운 배열 생성
if (index !== -1) {
newArray.splice(index, 1); // 새로운 배열에 변경사항 적용
} else {
newArray.push(brandId); // 새로운 배열에 변경사항 적용
}
state.brandIdList = newArray; // 기존 배열 대신 새로운 배열 할당
}