详解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),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容