Vue 官方文档对动态组件有以下描述:
有的时候,在不同组件之间进行动态切换是非常有用的,比如在一个多标签的界面里。上述内容可以通过 Vue 的 <component>
元素加一个特殊的 is
attribute 来实现。
我们写一个使用动态组件的简单例子。
<html>
<head>
<style type="text/css">
</style>
</head>
<body>
<script src="./vue.js"></script>
<div id="app" >
<component :is="currentView"></component>
</div>
<script>
var home = {
template : "<div>home page</div>",
mounted : function(){
console.log("home mounted")
}
};
var about = {
template : "<div>about page</div>",
mounted : function(){
console.log("about mounted")
}
}
var vm = new Vue({
el: '#app',
data: {
index : 0,
list: [home, about]
},
computed: {
currentView() {
return this.list[this.index];
}
}
})
setTimeout(() => {
vm.index = 1;
}, 5000);
</script>
</body>
</html>
先渲染了home page 5秒后变成了about page。有哪些不明白的地方可以留言。下一篇文章我们看看其中的原理。