vue组件-使用插槽分发内容(slot)
生活随笔
收集整理的這篇文章主要介紹了
vue组件-使用插槽分发内容(slot)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
slot--使用插槽分發內容(位置、槽口;作用: 占個位置)
官網API:?https://cn.vuejs.org/v2/guide/components.html#使用插槽分發內容
使用組件時,有時子組件不知道會收到什么內容,這是由父組件決定的。
一、單個插槽
1.my-component 組件: <div><h2>我是子組件的標題</h2><slot>只有在沒有要分發的內容時才會顯示。</slot> </div>2.父組件: <div><h1>我是父組件的標題</h1><my-component><p>這是一些初始內容</p><p>這是更多的初始內容</p></my-component> </div>3.渲染結果: <div><h1>我是父組件的標題</h1><div><h2>我是子組件的標題</h2><p>這是一些初始內容</p><p>這是更多的初始內容</p></div> </div>二、具名插槽
slot根據不同的name名稱分發內容,多個插槽可以有不同的名字。
仍然可以有匿名的默認插槽,為了找不到匹配的內容片段使用,如果沒有默認插槽,這些找不到匹配的內容片段將被拋棄。
1.my-component 組件: <div class="container"><header><slot name="header"></slot></header><main><slot></slot></main><footer><slot name="footer"></slot></footer> </div>2.父組件:<my-component><h1 slot="header">這里可能是一個頁面標題</h1><p>主要內容的一個段落。</p><p>另一個主要段落。</p><p slot="footer">這里有一些聯系信息</p> </my-component>3.渲染結果: <div class="container"><header><h1>這里可能是一個頁面標題</h1></header><main><p>主要內容的一個段落。</p><p>另一個主要段落。</p></main><footer><p>這里有一些聯系信息</p></footer> </div>三、作用域插槽
作用域插槽是一種特殊類型的插槽,用作一個 (能被傳遞數據的) 可重用模板,來代替已經渲染好的元素。
1.子組件: <div class="child"><slot text="hello from child"></slot> </div>2.父組件:<div class="parent"><child><template slot-scope="props"><span>hello from parent</span><span>{{ props.text }}</span></template></child> </div>3.渲染結果: <div class="parent"><div class="child"><span>hello from parent</span><span>hello from child</span></div> </div>?
更多專業前端知識,請上 【猿2048】www.mk2048.com
總結
以上是生活随笔為你收集整理的vue组件-使用插槽分发内容(slot)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ajax全接触(1)
- 下一篇: Vue node.js商城-购物车模块