动态的显示不同的组件:
实现方法:
- 在父组件的数据里面定义一个数据,用来记录当前展示组件名称,例如:currentItem
- 定义多个子组件
- 父组件里的模板中,添加 component 标签,其中绑定 is 属性:
<component :is="currentItem"></component>
这句代码等价于:
<input-item v-show="this.currentItem === 'input-item'" />
<img-item v-show="this.currentItem === 'img-item'" />
两者效果一样,上面的写法更精简
4. 如果希望切换组件时,保留组件切换前的状态,可以使用 <keep-alive> 标签,将
<component></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>
<style>
img {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="root">
</body>
<script>
const app = Vue.createApp({
data() {
return {
currentItem: "input-item"
}
},
methods: {
handleClick() {
if (this.currentItem === "input-item") {
this.currentItem = "img-item";
} else {
this.currentItem = "input-item";
}
}
},
template: `
<button @click="handleClick">切换</button>
<keep-alive>
<component :is="currentItem"></component>
</keep-alive>
`
});
app.component('input-item', {
template: `
<input type="text" placeholder="请输入今天的天气" />
`
});
app.component('img-item', {
template: `
<img src="images/头像3.jpg">
`
});
// 将Vue实例挂载到 id 名为 root 的 dom节点
app.mount('#root');
</script>
</html>