// store/search.ts
export const useSearchStore = defineStore('search', {
state: (): SearchState => ({
// ...
search: {}
// ...
}),
// ...
}
<!--...-->
<v-col v-if="reportStore.search.type === 'A'">
<!-- ... -->
<v-col>
//...
setup() {
const reportStore = useReportStore();
watch(
() => proxy.$route,
(to: Route) => {
if (to.name==='targetPage') {
reportStore.search.type = 'A';
}
}
return {reportStore}
}
//...
위 코드의 문제점은 무엇일까?
search.type
은 변경이 감지되지 않는다. (=reactive 하게 동작하지 않는다.)Vue는 반응형 속성을 동적으로 추가하는 것을 허용하지 않으므로, 빈 값을 사용하더라도 모든 루트 수준의 반응형 데이터 속성을 미리 선언하여 컴포넌트 인스턴스를 초기화해야 합니다.
// store/user.ts
export const useSearchStore = defineStore('search', {
state: (): SearchState => ({
// ...
search: {
// ...
type: 'DEFAULT',
// ...
}
// ...
}),
// ...
});
<!--...-->
<v-col v-if="search.type === 'A'">
<!-- ... -->
<v-col>
//...
setup() {
const { search } = useReportStore();
watch(
() => proxy.$route,
(to: Route) => {
if (to.name==='targetPage') {
search.type = 'A';
}
}
return { search }
}
//...
computed나, storeToRefs 작업 없이 reactive 하게 변수가 동작하여 더 간편한데 Object Type 으로 정의하지 않을 이유가 있을까?
// 이렇게 선언해 둔 경우, 초기화 시 search 객체가 그대로 남아있다.
search: {
// ...
type: 'DEFAULT',
// ...
}
const defineSearchStore = defineStore('search', {
state: (): SearchState => ({
search: null
}),
// ...
}
// searchStore 사용 시 search 객체 할당
export const useSearchStore = () => {
const store = defineSearchStore();
store.search = {
// ...
type: 'DEFAULT',
//...
}
return store;
}