VueJ에 컴포넌트를 재장착하는 방법
DOM 렌더링의 일부로 마운트된 컴포넌트가 있습니다.응용 프로그램의 골격은 다음과 같습니다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<div id="app">
<my-component></my-component>
<button>press this button to reload the component</button>
</div>
</body>
</html>
<my-component>
기능하고 있다(몇 가지 폼 입력이 표시된다).$emit
데이터를 부모에게 보냅니다.
다시 장착하는 방법이 있나요?목표는 컴포넌트 콘텐츠와 셋업을 처음 렌더링한 것처럼 하는 것입니다(클라이언트의 리셋 포함).data()
상태를 유지하는 요소).
이에 대한 몇 가지 해결책이 있지만, 그들은 모두 재작성을 전제로 하고 있다.data()
피하고 싶군요
제가 알기로는 컴포넌트는 렌더링 중에 돔에 올바른 위치에 삽입된 HTML/CSS/JS 코드이기 때문에 "재마운트"라는 개념은 존재하지 않습니다.data()-rewrite 방식으로 진행하기 전에 확인하고 싶었습니다.
비결은 열쇠를 바꾸는 것이다.
키가 변경되면 vue는 해당 키를 새 구성 요소로 간주하므로 "이전" 구성 요소를 마운트 해제하고 "새" 구성 요소를 마운트합니다.
예를 들어,created()
후크는 한 번만 실행되므로 값의 변화가 확인되면 완전히 새로운 개체가 표시됩니다.
예:
Vue.component('my-component', {
template: `<div>{{ rand }}</div>`,
data() {
return {
rand: ''
}
},
created() {
this.rand = Math.round(Math.random() * 1000)
}
});
new Vue({
el: '#app',
data: {
componentKey:0
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.8/vue.min.js"></script>
<div id="app">
<my-component :key="componentKey"></my-component>
<button @click="componentKey=!componentKey">press this button to reload the component</button>
</div>
템플릿에 v-if 지시문을 추가합니다.
<template>
<my-component v-if="renderComponent" />
</template>
스크립트에 nextTick을 사용하는 다음 메서드를 추가합니다.
<script>
export default {
data() {
return {
renderComponent: true,
};
},
methods: {
forceRerender() {
// Remove my-component from the DOM
this.renderComponent = false;
this.$nextTick(() => {
// Add the component back in
this.renderComponent = true;
});
}
}
};
</script>
여기서 일어나고 있는 일은 다음과 같습니다.
처음에 renderComponent가 true로 설정되므로 my-component가 렌더링됩니다. forceRender를 호출하면 즉시 false로 설정됩니다. 이제 v-if 지시문이 false로 평가되므로 my-component 렌더링을 중지합니다. 다음 trenderComponent는 true로 다시 설정됩니다. 이제 v-if 지시문이 trender가 true로 평가되므로 my-component 렌더링을 시작합니다.다시 한 번
언급URL : https://stackoverflow.com/questions/47459837/how-to-re-mount-a-component-in-vuejs
'programing' 카테고리의 다른 글
vue 속성 "$v"의 vuelidate가 렌더링 중에 액세스되었지만 인스턴스에서 정의되지 않았습니다. (0) | 2022.08.30 |
---|---|
페이로드에 전달된 Vuex 어레이 변환 (0) | 2022.08.30 |
Vue.js - v-for 내에서 필터 사용 (0) | 2022.08.30 |
Vue - Axios 응답에서 하위 구성 요소의 데이터를 전달합니다. (0) | 2022.08.30 |
오류: PostCSS 플러그인을 로드하지 못했습니다. 'postcss-import' 모듈을 찾을 수 없습니다(Vue 2). (0) | 2022.08.30 |