1. 程式人生 > 程式設計 >淺談Vue中插槽slot的使用方法

淺談Vue中插槽slot的使用方法

如何定義和使用:

在元件的template中使用slot標籤定義,slot標籤中間可以定義預設顯示值,如果slot標籤沒有宣告name屬性值,在使用插槽時將預設從第一個插槽依次往下放置,為了方便使用,一般都會都插槽slot指定一個name屬性值,當要使用該插槽時,只需要在要使用的標籤內新增slot=‘插槽名字',就可以將指定的標籤放到指定的插槽內,插槽內可以是任意內容。

舉例:

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta
http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>slot插槽練習</title> <script src=oIeeJ"../..//.js"></script> </head> <body> <div id="app"> <div style="border: 7px solid blueviolet;"> <h2>父元件</h2> <cpn> <!-- 將一個元素新增到指定得插槽位置 --> <button slot="left">按鈕</button> <input type="text" slot="right" placeholder="這是輸入框..."></input> </cpn> </div> </div> <template lang="" id="cpn"> <div style="border: 6px solid green;"> <h2>子元件</h2> <!-- 在子元件中定義三個插槽,插槽內得值為預設值 --> <slot name="left">左</slot> <slot name="mediate">中</slot> <slot name="right">右&lhttp://www.cppcns.com
t;/slot> </div> </template> <script> new Vue({ el:'#app',components:{ cpn:{客棧 template:'#cpn',} } }) </script> </body> </html>

效果如圖:

淺談Vue中插槽slot的使用方法

分析:

在上面例項中,子元件中定義了三個插槽,並給了具體的name屬性值,在父元件呼叫子元件中,子元件內給name為left的插槽位置放置了一個按鈕,將並將一個輸入框oIeeJ

放置到name為right的插槽。從中我們可以發現,通過使用插槽,可以使元件有更多的擴充套件,插槽內的內容可以是任意內容,定義插槽,相當於提前給元件挖好一個坑,等後面用到的時候再呼叫。


到此這篇關於 淺談Vue中插槽slot的使用方法的文章就介紹到這了,更多相關Vue中插槽slot用法內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!