sourcecode

VueJ: 감시자 내부에서 구성 요소 속성을 업데이트할 수 없습니다.

copyscript 2022. 7. 28. 23:42
반응형

VueJ: 감시자 내부에서 구성 요소 속성을 업데이트할 수 없습니다.

저는 Vuex를 사용하는 Vue 2 Webpack 어플리케이션을 만들고 있습니다.Vuex 스토어에서 데이터를 가져오는 계산된 속성을 보고 구성 요소의 로컬 상태를 업데이트하려고 합니다.이게 그 내부입니다.<script></script>컴포넌트의 섹션은 다음과 같습니다.

export default {
    name: 'MyComponent',

    data() {
        return {
            // UI
            modal: {
            classes: {
                'modal__show-modal': false,
            },
            tags: [],
            },
        };
    },

    computed: {
        tagList() {
            return this.$store.getters.tagList;
        },
    },

    watch: {
        tagList: (updatedList) => {
            this.modal.tags = updatedList;
        },
    },
};

보시는 바와 같이 저는 tagList라는 계산 속성을 가지고 있습니다.이 속성은 스토어에서 데이터를 가져옵니다.매장 데이터가 변경될 때마다 업데이트할 수 있도록 tagList를 감시하는 감시자가 있습니다.modal.tags새로운 가치를 실현합니다.

Vue 설명서에 따르면this.propertyName로컬 컴포넌트 상태를 업데이트 할 수 있지만this.modal.tags = updatedList;, 다음의 에러가 표시됩니다.

[Vue warn]: Error in callback for watcher "tagList": "TypeError: Cannot set property 'tags' of undefined"

이 에러는, Vue.js 의 메뉴얼에 기재되어 있는 에러와 다르지 않습니다만, 왜 발생하는 것입니까.

화살표 기능을 사용하지 마십시오.

변경처:

watch: {
    tagList: (updatedList) => {
        this.modal.tags = updatedList;
    },
},

수신인:

watch: {
    tagList(updatedList) {              // changed this line
        this.modal.tags = updatedList;
    },
},

Vue documents에서는 이 점에 대해 여러 번 언급하고 있습니다.

옵션 속성 또는 콜백에 화살표 기능을 사용하지 마십시오.created: () => console.log(this.a)또는vm.$watch('a', newValue => this.myMethod())화살표 함수는 부모 컨텍스트에 바인딩되어 있기 때문에thisVue 인스턴스가 예상대로 되지 않아 종종 다음과 같은 오류가 발생합니다.

Uncaught TypeError: Cannot read property of undefined

또는

Uncaught TypeError: this.myMethod is not a function

이것은 기본적으로 컨텍스트/범위 문제입니다.화살표 기능을 사용할 경우thisVue 인스턴스가 아니라 컴포넌트가 선언된 장소(아마도)를 포함하는 컨텍스트를 참조합니다.window).

그것은 범위 문제 때문입니다.전화하고 있습니다.this.다른 문맥에서.따라서 화살표 기능에서는 vuejs 데이터에 액세스할 수 없습니다.

시계를 다음과 같이 변경할 것을 권장합니다.

tagList (updatedList) {
    this.modal.tags = updatedList;
},

언급URL : https://stackoverflow.com/questions/49580275/vuejs-unable-to-update-a-component-property-from-inside-a-watcher

반응형