programing

vue watch mapState가 작동하지 않음

randomtip 2022. 8. 31. 22:02
반응형

vue watch mapState가 작동하지 않음

컴포넌트에 스토어 값을 사용하여 업데이트를 시도합니다.버튼을 클릭하면 스토어 값이 변경되지만 변경 내용이 컴포넌트 출력에 반영되지 않습니다(예: {{query}).

    <template>
         span {{query}}
         button(@click='updateQuery')
    </template>

    <script>
    export default {
        computed: mapState('map', [
            'query'
        ]),
        methods: {
            ...mapMutations('map', [
                'setStart'
            ]),
            updateQuery() {
                this.setStart(new Date());
            }
       }
   }
   </script>

스토어:

export default {
    namespaced: true,
    state: {
        query: {},
        start: null,
        end: null
    },
    mutations: {
        setQuery(state, value) { state.query = value },
        setStart(state, value) {
            state.start = value;
            state.query.timestamp = state.query.timestamp ? state.query.timestamp : {};
            state.query.timestamp.$gte = value;
        },
        setEnd(state, value) {
            state.end = value;
            state.query.timestamp = state.query.timestamp ? state.query.timestamp : {};
            state.query.timestamp.$lte = value;
        },
    }
}

여기서의 문제는 Vue가 새로운 속성을 추가 중임을 감지할 수 없다는 것입니다.query동적으로 오브젝트

이 코드에서는:

state.query.timestamp = state.query.timestamp ? state.query.timestamp : {};

추가하려고 합니다.timestamp의 재산.query그전에는 없었던 것 같아요.따라서 반응하지 않습니다.Vue를 올바르게 사용하려면 Vue.set을 사용해야 합니다.

Vue.set(state.query, `timestamp`, state.query.timestamp ? state.query.timestamp : {})

주의: 이 작업은 다음 줄에서도 수행해야 합니다.$gte소유물.

또는 쿼리 개체를 초기화할 수 있습니다.

state: {
    query: {
      timestamp:{
        $gte: null,
        $lte: null
      }
    },
    start: null,
    end: null
},

언급URL : https://stackoverflow.com/questions/44888440/vue-watch-mapstate-not-working

반응형