一、动态组件
1、动态组件
# <component :is="who"></component>
# component标签的is属性等于组件名字,这里就会显示这个组件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <button @click="who='home'">首页</button> <button @click="who='good'">商品</button> <button @click="who='order'">订单</button> <hr> <component :is="who"></component> </div> </body> <script> var home = { template: ` <div> <h1>首页</h1> </div> ` } var good = { template: ` <div> <h1>商品页面</h1> </div> ` } var order = { template: ` <div> <h1>订单页面</h1> </div> ` } var vm = new Vue({ el: '#app', data: { who: 'home' }, components: { home, good, order } }) </script> </html>
2、效果:点什么弹出什么
3、保存输入的记录
<keep-alive>
<component :is="who"></component>
</keep-alive>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <button @click="who='home'">首页</button> <button @click="who='good'">商品</button> <button @click="who='order'">订单</button> <hr> <keep-alive> <component :is="who"></component> </keep-alive> </div> </body> <script> var home = { template: ` <div> <h1>首页</h1> </div> ` } var good = { template: ` <div> <h1>商品页面</h1> <p>搜索商品:<input type="text" v-model="name"> <button @click="handleSearch">搜索</button> </p> </div> `, data() { return { name: '' } }, methods: { handleSearch() { alert(this.name) } } } var order = { template: ` <div> <h1>订单页面</h1> </div> ` } var vm = new Vue({ el: '#app', data: { who: 'home' }, components: { home, good, order } }) </script> </html>
二、插槽