您好,登錄后才能下訂單哦!
如何在vue中使用slot插槽?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://unpkg.com/vue@2.3.3/dist/vue.js"></script> </head> <body> <div id="app"> <div> <!-- 單slot --> <v-one> <!-- 這里的所有內(nèi)容會替換掉slot --> <p>初始化段落一</p> <p>初始化段落二</p> </v-one> <!-- 渲染結(jié)果 --> <!-- <div> <h2>組件標(biāo)題</h2> <p>初始化段落一</p> <p>初始化段落二</p> <p>組件段落內(nèi)容</p> <p>I am one</p> </div> --> <!-- 具名slot --> <v-two> <p slot="nav">我是導(dǎo)航</p> <p slot="main">我是內(nèi)容</p> <p slot="footer">我是底部</p> </v-two> <!-- 渲染結(jié)果 --> <!-- <div> <nav> <p>我是導(dǎo)航</p> </nav> <main> <p>我是內(nèi)容</p> </main> <footer> <p>我是底部</p> </footer> </div> --> <!-- 作用域插槽 --> <v-three> <!-- 父組件默認(rèn)無法使用子組件數(shù)據(jù) --> <template scope="props"> <p>{{props.text}}</p> </template> </v-three> <!-- 渲染結(jié)果 --> <!-- <div><p>I am three</p></div> --> </div> </div> <template id="one"> <div> <h2>組件標(biāo)題</h2> <slot></slot> <p>組件段落內(nèi)容</p> <p>{{one}}</p> </div> </template> <!-- 具名slot --> <template id="two"> <div> <nav> <slot name="nav"></slot> </nav> <main> <slot name="main"></slot> </main> <footer> <slot name="footer"></slot> </footer> </div> </template> <!-- 作用域插槽 --> <template id="three"> <div> <!-- 把數(shù)據(jù)傳遞給slot,這樣父組件也可以訪問three這個組件的數(shù)據(jù) --> <slot :text="three"></slot> </div> </template> <script> new Vue({ el: '#app', components: { 'v-one': { template: '#one', data() { return { 'one': 'I am one' } } }, 'v-two': { template: '#two', data() { return { 'two': 'I am two' } } }, 'v-three': { template: '#three', data() { return { 'three': 'I am three' } } } } }); </script> </body> </html>
單個slot使用最簡單,也是最常用的,當(dāng)我們定義了一個子組件,父組件在使用的這個組件的時候,想在內(nèi)部自定義一些初始化數(shù)據(jù),這時候就可以用slot實現(xiàn)。
具名slot只是給slot加了name屬性,在使用的時候可以引入多個。
作用域slot就比較強(qiáng)大了,我們知道子組件的數(shù)據(jù),在父組件中是無法使用的,但是通過官方提供的擴(kuò)展,可以輕松實現(xiàn)這一點。
渲染后效果圖,可以直接自己在瀏覽器運行查看效果
關(guān)于如何在vue中使用slot插槽問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。