动态渲染一个组件。
<component v-bind:is="currentTabComponent"></component>
??????? 默认情况下,当组件在切换的时候都会重新创建组件,但是有些时候我们希望组件实例能够被在它们第一次被创建的时候缓存下来。为了解决这个问题,我们可以用一个 <keep-alive> 元素将其动态组件包裹起来。
<keep-alive> ?? ?<component v-bind:is="currentTabComponent"></component> </keep-alive>
<!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="../js/vue.js"></script>
</head>
<body>
<div id="app">
<div>
<button @click="current = 'my-com1'">组件一</button>
<button @click="current = 'my-com2'">组件二</button>
</div>
<!-- <my-com1 v-if="isActive"></my-com1>
<my-com2 v-else></my-com2> -->
<component :is="current">
</component>
</div>
<script>
let compon1 = {
data() {
return {}
},
template: `
<div>
<p>我是组件一</p>
</div>
`
}
let compon2 = {
data() {
return {}
},
template: `
<div>
<p>我是组件二</p>
</div>
`
}
let vm = new Vue({
el: "#app",
data: {
isActive: true,
current: 'my-com1'
},
methods: {
},
created() {
},
components: {
myCom1: compon1,
myCom2: compon2,
}
})
</script>
</body>
</html>
|