所谓动态组件: 根据数据的变化, 结合 component 标签, 随时动态切换组件的显示或隐藏
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
const app = Vue.createApp({
data() {
return {
currentItem: "my-title",
};
},
methods: {
handleClick() {
if (this.currentItem === "my-title") {
this.currentItem = "my-input";
} else {
this.currentItem = "my-title";
}
},
},
template: `
<my-input v-show="currentItem==='my-input'" />
<my-title v-show="currentItem==='my-title'" />
<button v-on:click="handleClick">切换</button>
`,
template:`
<keep-alive>
<component :is="currentItem" />
</keep-alive>
<button v-on:click="handleClick">切换</button>
`
});
app.component("my-input", {
template: `
<input type="text"/>
`,
});
app.component("my-title", {
template: `
<h1>hello world</h1>
`,
});
const vm = app.mount("#root");
</script>
</html>