vue——進階
阿新 • • 發佈:2020-12-17
一、
a. 單個slot
b. 具名slot
*混合父元件的內容與子元件自己的模板-->內容分發
*父元件模板的內容在父元件作用域內編譯;子元件模板的內容在子元件作用域內編譯。
#指定元件的樣式,只用元件的功能
哪裡需要就在哪裡放插槽: <slot></slot>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script> <title>Title</title> </head> <body> <div id="box">
//不使用插槽的話,child1裡的內容1 2 3 4 顯示不出來,哪裡寫了插槽就在哪裡顯示
<child1> <ul> <li v-for="i in 4">{{i}}</li> </ul> </child1> <hr> <child2></child2> <hr> <child3></child3> </div> </body> <script> var vm = new Vue({ el: '#box', data: { who: 'child1' }, components: { child1: { template: ` <div> <slot></slot> <hr> 我是首頁 <slot></slot> </div> `, }, child2: { template: ` <div>我是商品 </div> `, }, child3: { template: ` <div>我是訂單 </div> `, } } }) </script> </html>
1.2插槽小案例(
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script> <title>Title</title> </head> <body> <div id="box"> <child1> <button @click="isShow=!isShow">點我隱藏child2</button> </child1> <hr> <child2 v-if="isShow"></child2> </div> </body> <script> var vm = new Vue({ el: '#box', data: { isShow: true, }, components: { child1: { template: ` <div> <slot></slot> </div> `, }, child2: { template: ` <div> <ul> <li v-for="i in 4">{{i}}</li> </ul> </div> `, }, } }) </script> </html>
1.3
程式碼演示: 點選隱藏child2,通過名字來指定
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script> <title>Title</title> </head> <body> <div id="box"> <child1> <button @click="isShow=!isShow" slot="button1">點我隱藏child2</button> <div slot="div1">我是div</div> </child1> <hr> <child2 v-if="isShow"></child2> </div> </body> <script> var vm = new Vue({ el: '#box', data: { isShow: true, }, components: { child1: { template: ` <div> <slot name="button1"></slot> <hr> <slot name="div1"></slot> </div> `, }, child2: { template: ` <div> <ul> <li v-for="i in 4">{{i}}</li> </ul> </div> `, }, } }) </script> </html>