programing

특정 값이 채워졌을 때 Vue.js 구성 요소에서 메서드를 호출하는 방법(단 한 번만)

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

특정 값이 채워졌을 때 Vue.js 구성 요소에서 메서드를 호출하는 방법(단 한 번만)

Vue.js(현재는 v2.6.11)를 사용하는 어플리케이션에서 작업하고 있는데 어플리케이션이 커짐에 따라 패턴이 자주 나타납니다.몇 가지 기능을 추상화하고 싶기 때문에 새로운 컴포넌트를 추출합니다만, 이 컴포넌트를 복사하면mounted상위에서 하위로 후크하면 이전에 사용 가능했던 일부 데이터가 정의되지 않습니다.데이터가 소품에서 오는 경우도 있고 Vuex 스토어에서 오는 경우도 있습니다.

당초의 생각과는 달리, 내부 컴포넌트가 외부 컴포넌트보다 먼저 초기화되어 있는 것이 문제의 원인이라고 생각합니다.

다음은 예를 제시하겠습니다.

상위 컴포넌트

<template>
    <div class="options-container">
        <features-list />
    </div>
</template>
<script>
import { mapGetters } from 'vuex';
import FeaturesList from '../features/FeaturesList.vue';

export default {
    name: 'ProductComponent',
    components: {
        FeaturesList,
    },
    computed: {
        ...mapGetters('product', [
            'userSelection',
        ]),
    },
    mounted() {
        // here I can call the methods which rely on UserSelections
        // the variable UserSelections has already a value here
        const params = this.getTemplateCollectionParams();
        this.getTemplateAssets(params);
    },
};
</script>

하위 구성 요소

<template>
    <div class="options">
        <template v-for="key in sortedFeaturesLayout">
            <feature-base-component
                :option="options[key]"
                :key="key"
                v-on="$listeners"
            />
        </template>
    </div>
</template>
<script>
import FeatureBaseComponent from './FeatureBaseComponent.vue';
import { mapGetters } from 'vuex';

export default {
    name: 'FeaturesList',
    components: {
        FeatureBaseComponent,
    },
    computed: {
        ...mapGetters('product', [
            'userSelection',
        ]),
    },
    methods: {
        getTemplateCollectionParams() {
            // ...
        },
        getTemplateAssets(params) {
            // ...
        },
    },
    mounted() {
        // here I have an error because `userSelection` is still empty
        const params = this.getTemplateCollectionParams();
        this.getTemplateAssets(params);
    },
};
</script>

제가 주로 하는 일은 값에서 워처를 만들고 워처 업데이트 시 함수를 호출하는 것입니다.원래 코드가 한 번만 실행되었으므로 이 메서드가 한 번만 호출되는지 확인하고 싶기 때문에 이 코드가 이미 실행되었는지 확인하는 부울을 추가합니다.

<template>
    <div class="options">
        <template v-for="key in sortedFeaturesLayout">
            <feature-base-component
                :option="options[key]"
                :key="key"
                v-on="$listeners"
            />
        </template>
    </div>
</template>
<script>
import FeatureBaseComponent from './FeatureBaseComponent.vue';
import { mapGetters } from 'vuex';

export default {
    name: 'FeaturesList',
    components: {
        FeatureBaseComponent,
    },
    data() {
        return {
            isFirstLoad: true,
        };
    },
    computed: {
        ...mapGetters('product', [
            'userSelection',
        ]),
    },
    methods: {
        getTemplateCollectionParams() {
            // ...
        },
        getTemplateAssets(params) {
            // ...
        },
    },
    watch: {
        userSelection() {
            // get gallery
            if (this.isFirstLoad) {
                // here I need the getter userSelection which is empty on `mounted`
                const params = this.getTemplateCollectionParams();
                this.getTemplateAssets(params);
                this.isFirstLoad = false;
            }
        },
    },
};
</script>

나는 내가 하고 있는 일이 완전히 틀린 것은 아니라고 생각한다.다만, 소품에만 사용되는 부란이 많아지는 경우가 있기 때문에, 처음에 소품이 가치가 있을 때만 방법을 실행하는 보다 깔끔한 방법은 없을까 생각하고 있습니다.

또는 를 사용할 수도 있습니다.unwatch다음 콜백을 정지하기 위해 호출할 수 있는 함수:

const unwatch = this.$watch('userSelection', userSelection => {
  //...

  // stop watching
  unwatch()
})

이를 통해 워치핸들러가 이미 호출되었는지 확인하기 위해 추가 플래그가 필요하지 않고 워처가 호출된 적이1번밖에 없습니다.

편집 Vue에서 값 연결 해제

언급URL : https://stackoverflow.com/questions/63523812/how-to-call-a-method-on-a-vue-js-component-when-a-particular-value-is-populated

반응형