vue的slot1、什麼是slot
slot是插槽,插即是可以插入,槽就是坑,即是可以再代碼中插入
如果子組件模板中不包含插口,那麼父組件的內容將會被丟棄。當子組件模板中有一個麼有屬性的插槽時,父組件傳入的整個內容片段,將插入到插槽所在的dom的位置,並替換掉插槽標籤本身。
舉例:
<html> <head> <meta charset="utf-8"> <title>Vue 父子組件通信之子組件索引</title> </head> <body> <div id="app"> <child-component> <p>正文內容</p> <p>更多的正文內容</p> </child-component> </div> <script src="https://unpkg.com/vue/dist/vue.min.js"></script> <script> Vue.component('child-component', { template: '\ <div>\ <div>\ </div>\ <div>\ <div>\ <div>\ <div>\ </div>' }) var app = new Vue({ el: '#app', }) </script> </body></html>
<html> <head> <meta charset="utf-8"> <title>Vue 父子組件通信之子組件索引</title> </head> <body> <div id="app"> <child-component> <h2 slot="header">標題</h2> <p>正文內容</p> <p>更多的正文內容</p> <div slot="footer">底部信息</div> </child-component> </div> <script src="https://unpkg.com/vue/dist/vue.min.js"></script> <script> Vue.component('child-component', { template: '\ <div>\ <div>\ </div>\ <div>\ <slot ></slot>\ <slot name="header" ></slot>\ <div>\ <div>\ <div>\ </div>' }) var app = new Vue({ el: '#app', }) </script> </body></html>
作用域是指:子組件中的數據,在父組件中可以被引用。
<html> <head> <meta charset="utf-8"> <title>Vue 父子組件通信之子組件索引</title> </head> <body> <div id="app"> <child-component> <h2 slot="header">標題</h2> <p>正文內容</p> <p>更多的正文內容</p> <div slot="test" slot-scope="testMore"> {{testMore.testText}} </div> <div slot="footer">底部信息</div> </child-component> </div> <script src="https://unpkg.com/vue/dist/vue.min.js"></script> <script> Vue.component('child-component', { template: '\ <div>\ <div>\ </div>\ <div>\ <slot ></slot>\ <slot name="test" testText="作用域文字"></slot>\ <slot name="header" ></slot>\ <div>\ <div>\ <div>\ </div>' }) var app = new Vue({ el: '#app', }) </script> </body></html>
參考網址:https://www.jianshu.com/p/0d8952ff4227