Vue 组件 - 动态组件
Vue 渐进式JavaScript 框架 基于Vue2的学习笔记 - Vue 组件 - 动态组件
目录
动态组件
选项卡页面示例
更简单写法
增加输入框
弥补措施
总结
动态组件
选项卡页面示例
功能:选项卡功能,设置导航点击哪个显示相应页面。
设置三个全局组件,并在页面中调用;在组件的下方设置触发导航。
示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
footer ul {
margin-top:200px;
float:left;
background-color: #ccc;
list-style: none;
}
footer ul li {
width:100px;
height: 20px;
float:left;
line-height: 20px;
text-align: center;
}
</style>
<script src="../lib/vue.js"></script>
</head>
<body>
<div id="box">
<home v-show=" which === 'home'"></home>
<list v-show=" which === 'list'"></list>
<shopcar v-show=" which === 'shopcar'"></shopcar>
<footer>
<ul>
<li @click=" which='home'">首页</li>
<li @click=" which='list'">列表</li>
<li @click=" which='shopcar'">购物车</li>
</ul>
</footer>
</div>
<script>
Vue.component("home", {
template:`
<div>
home
</div>
`
})
Vue.component("list", {
template:`
<div>
list
</div>
`
})
Vue.component("shopcar", {
template:`
<div>
shopcar
</div>
`
})
let vm = new Vue({
el: "#box",
data: {
which:'home'
}
})
</script>
</body>
</html>
效果如下:
更简单写法
使用component组件优化原有写法。
Component是组件控件,is是固定属性;动态绑定状态即可。
示例如下:
<div id="box">
<!--<home v-show=" which === 'home'"></home>
<list v-show=" which === 'list'"></list>
<shopcar v-show=" which === 'shopcar'"></shopcar>-->
<component :is="which"></component>
<footer>
<ul>
<li @click=" which='home'">首页</li>
<li @click=" which='list'">列表</li>
<li @click=" which='shopcar'">购物车</li>
</ul>
</footer>
</div>
动态组件缺点是适配性不好,无法复用。
增加输入框
每个组件都有一个输入框、搜索框,当切换组件后,输入框中的内容无法复用。
在home组件中增加输入框,切换组件后发现原有输入内容消失了。
示例如下:
Vue.component("home", {
template:`
<div>
home
<input type="text">
</div>
`
})
弥补措施
保持活着,首先把数据加载到内存中,等组件创建后再临时从内存中读出来,显示出来。
示例如下:
<keep-alive>
<component :is="which"></component>
</keep-alive>
总结
Vue 渐进式JavaScript 框架 基于Vue2的学习笔记 - Vue 组件 - 动态组件