官方文檔其實已經講得很詳細,我根據文檔,把官方的小案例實現了一下,這樣更直觀
<!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> <!-- 這里的所有內容會替換掉slot --> <p>初始化段落一</p> <p>初始化段落二</p> </v-one> <!-- 渲染結果 --> <!-- <div> <h1>組件標題</h1> <p>初始化段落一</p> <p>初始化段落二</p> <p>組件段落內容</p> <p>I am one</p> </div> --> <!-- 具名slot --> <v-two> <p slot="nav">我是導航</p> <p slot="main">我是內容</p> <p slot="footer">我是底部</p> </v-two> <!-- 渲染結果 --> <!-- <div> <nav> <p>我是導航</p> </nav> <main> <p>我是內容</p> </main> <footer> <p>我是底部</p> </footer> </div> --> <!-- 作用域插槽 --> <v-three> <!-- 父組件默認無法使用子組件數據 --> <template scope="props"> <p>{{props.text}}</p> </template> </v-three> <!-- 渲染結果 --> <!-- <div><p>I am three</p></div> --> </div> </div> <template id="one"> <div> <h1>組件標題</h1> <slot></slot> <p>組件段落內容</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> <!-- 把數據傳遞給slot,這樣父組件也可以訪問three這個組件的數據 --> <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使用最簡單,也是最常用的,當我們定義了一個子組件,父組件在使用的這個組件的時候,想在內部自定義一些初始化數據,這時候就可以用slot實現。
具名slot只是給slot加了name屬性,在使用的時候可以引入多個。
作用域slot就比較強大了,我們知道子組件的數據,在父組件中是無法使用的,但是通過官方提供的擴展,可以輕松實現這一點。
渲染后效果圖,可以直接自己在瀏覽器運行查看效果
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答