1. 程式人生 > 實用技巧 >詳解Vue.js 作用域、slot用法(單個slot、具名slot)

詳解Vue.js 作用域、slot用法(單個slot、具名slot)

作用域

在介紹slot前,需要先知道一個概念:編譯的作用域。比如父元件中有如下模板:

<child-component>
 {{message}}
<child-component>

這裡的message就是一個slot,但是它繫結的是父元件的資料,而不是元件< child-component >的資料。

父元件模板的內容是在父元件作用域內編譯,子元件模板的內容是在子元件作用域內編譯。

<div id="app">
 <child-component v-show="showChild"></child-component>
</div>
<script>
 Vue.component('child-component',{
 template: '<div>子元件</div>'
 });

 var app = new Vue({
 el: '#app',
 data: {
  showChild: true
 }
 });
</script>

這裡的狀態showChild繫結的是父元件的資料,如果想在子元件上繫結,那應該是:

<div id="app">
 <child-component></child-component>
</div>
<script>
 Vue.component('child-component',{
 template: '<div v-show="showChild">子元件</div>',
 data: function () {
  showChild: true
 }
 });

 var app = new Vue({
 el: '#app'
 });
</script>

因此,slot分發的內容,作用域是在父元件上的。

slot用法

單個slot:

在子元件使用特殊的< slot >元素就可以為這個子元件開啟一個 slot(插槽),在父元件模板裡,插入在子元件標籤內的所有內容將替代子元件的< slot >標籤及它的內容。

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <script src="https://unpkg.com/vue/dist/vue.js"></script>
 <title>單個slot</title>
</head>
<body>
 <div id="app">
 <cild-component>
  <p>分發的內容</p>
  <p>更多分發的內容</p>
 </cild-component>
 </div>
 <script>
 Vue.component('child-component',{
  template: '\
  <div>\
   <slot>\
   <p>如果父元件沒有插入內容,我將作為默認出現</p>\
   </slot>\
  </div>'
 });

 var app = new Vue({
  el: '#app'
 });
 </script>
</body>
</html>

子元件child-component的模板內定義了一個< slot >元素,並且用一個< p >作為預設的內容,在父元件沒有使用slot時,會渲染這段預設的文字;如果寫入了slot,那就會替代整個< slot >標籤。

上面示例渲染後的結果為:

<div id="app">
 <div>
 <p>分發的內容</p>
 <p>更多分發的內容</p>
 </div>
</div>

注意:子元件< slot >內的為備用內容,它的作用域是子元件本身。

具名slot:

給< slot >元素指定一個name後可以分發多個內容,具名slot可以與單個slot共存。

<div id="myApp">
 <child-component>
 <h2 slot="header">標題</h2>
 <p>正文內容</p>
 <p>更多的正文內容</p>
 <div slot="footer">底部資訊</div>
 </child-component>
</div>
<script>
 Vue.component('child-component',{
 template: '\
  <div class="container">\
  <div class="header">\
   <slot name="header"></slot>\
  </div>\
  <div class="main">\
   <slot></slot>\
  </div>\
  <div class="footer">\
   <slot name="footer"></slot>\
  </div>\
  </div>'
 });

 var myApp = new Vue({
 el: '#myApp'
 });
</script>

子元件內聲明瞭3個< slot >元素,其中在< div class=“main” > 內的 < slot >沒有使用name特性,它將作為預設slot出現,父元件沒有使用slot特性的元素與內容都將出現在這裡。

如果沒有制定預設的匿名slot,父元件內多於的內容片斷都將被拋棄。

渲染結果:

<div class="container">
 <div class="header">
 <h2>標題</h2>
 </div>
 <div class="main">
 <p>正文內容</p>
 <p>更多的正文內容</p>
 </div>
 <div class="footer">
 <div slot="footer">底部資訊</div>
 </div>
</div>

總結

以上所述是小編給大家介紹的Vue.js 作用域、slot用法(單個slot、具名slot),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對碼農教程網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!