[英]vuejs - how to Passing props and event dynamically to dynamic component
[英]How dynamically change the component with object for props in vueJS
你知道如何使用 object prop 動態更改組件嗎
應用程序.vue
<template>
<div id="app">
<component :is="current['test'].target.name"> </component>
<input type="button" value="click me" @click="change" />
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
import Comp from "./components/Comp.vue";
export default {
name: "App",
components: {
HelloWorld,
Comp,
},
data() {
return {
current: {},
};
},
created() {
this.current["test"] = {
index: 0,
target: {
name: "Comp",
},
};
},
methods: {
change() {
const r =
this.current["test"].target.name === "HelloWorld"
? "Comp"
: "HelloWorld";
this.current["test"].target = {
name: r,
};
console.log(this.current["test"]);
},
},
};
</script>
比較
<template>
<p>Template 2</p>
</template>
你好世界.vue
<template>
<p>Template 1</p>
</template>
https://codesandbox.io/s/clever-water-dgbts?file=/src/components/HelloWorld.vue:0-42
對象的值將正確更改,但組件不會更改。
謝謝
這里的問題是屬性test
沒有在數據定義中的current
對象上定義 - 您在created()
函數中設置定義。 這意味着 Vue 不知道為該屬性創建響應式 getter/setter。
將數據定義更改為:
data() {
return {
current: {
test: {
index: 0,
target: {
name: "Comp"
}
}
}
};
}
由於 Vue 的反應方式(需要預定義的屬性),我建議不要將屬性作為字典項訪問,即使用:
current.test.target.name
代替
current['test'].target.name
有關 Vue 反應性的更多信息,請參閱此頁面:鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.