반응형
Vue.js의 상위 컴포넌트에서 동적 컴포넌트로 데이터 전달
상위 구성 요소에서 동적 구성 요소의 데이터를 설정하려고 합니다.
예: 부모 컴포넌트:
<div id="app">
<template v-for="(component, index) in components">
<component :is="component" :key="index"></component>
</template>
<button @click="add()">Add Component</button>
</div>
동적 컴포넌트:
let dynamicComponent = {
template: `
<p>Welcome {{ msg }}!</p>
`,
data () {
return {
msg: 'home'
}
},
}
const App = new Vue({
el: '#app',
data: {
components: [
dynamicComponent
]
},
methods: {
add () {
this.components.push(dynamicComponent);
},
}
});
새로운 동적 컴포넌트가 추가되었을 때 부모 컴포넌트에서 동적 컴포넌트의 데이터를 설정하고 싶습니다.
이 경우 부모 컴포넌트의 dynamic Component의 msg 속성
이런 걸 써야 돼요.props:['msg']
구성 요소에서
let dynamicComponent = {
template: `
<p>Welcome {{ msg2 }}, {{ msg }}!</p>
`,
props:['msg'],
data () {
return {
msg2: 'component message'
}
},
}
const App = new Vue({
el: '#app',
data: {
components: [
dynamicComponent
],
parentMsg:'parent message'
},
methods: {
add () {
this.components.push(dynamicComponent);
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<div id="app">
<template v-for="(component, index) in components">
<component :msg="parentMsg" :is="component" :key="index"></component>
</template>
<button @click="add()">Add Component</button>
<input type="text" v-model="parentMsg">
</div>
다음과 같이 할 수 있을 것 같습니다.
부모 템플릿:
<div id="app">
<template v-for="(component, index) in components">
// Add :msg to pass 'msg' to child component.
<component :is="component" :key="index" :msg="msg"></component>
</template>
<button @click="add()">Add Component</button>
</div>
Js:
let dynamicComponent = {
props: ['msg'], //<-- Specify the child will receive a prop 'msg'
template: `<p>Welcome {{ msg }}!</p>`
}
const App = new Vue({
el: '#app',
data: {
components: [
dynamicComponent
],
msg: 'Hello' //<-- Set the value of 'msg'
},
methods: {
add() {
this.components.push(dynamicComponent);
},
}
});
언급URL : https://stackoverflow.com/questions/59641041/passing-data-to-dynamic-component-from-parent-component-in-vue-js
반응형
'programing' 카테고리의 다른 글
vue-resource를 사용하여 jsonp를 가져오는 방법 (0) | 2022.08.15 |
---|---|
CSP에서 'unsafe-eval'을 사용하지 않는 Vuejs 브라우저 확장 (0) | 2022.08.15 |
Vuex에서 변환 또는 액션 내에서 공유 도우미 함수를 호출하는 방법 (0) | 2022.08.15 |
Vue 개체를 요소에 연결할 때 가장 권장되는 구문은 무엇입니까? (0) | 2022.08.15 |
메이븐의 '폼' 패키지는 무엇입니까? (0) | 2022.08.15 |