当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue学习笔记之slot插槽用法实例分析

vue学习笔记之slot插槽用法实例分析

2020年05月10日  | 移动技术网IT编程  | 我要评论

本文实例讲述了vue slot插槽用法。分享给大家供大家参考,具体如下:

不使用插槽,在template中用v-html解析父组件传来的带有标签的content

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
  <child content="<p>rachel</p>"></child>
</div>
</body>
</html>
<script>
  vue.component('child', {
    props: ['content'],
    template: '<div>
            <p>hello</p>
            <div v-html="this.content"></div>
          </div>'
  })
 
  var vm = new vue({
    el: '#app'
  })
</script>

使用插槽,如果父组件为空,就会显示slot中定义的默认内容

<child>
  <p>rachel</p>
</child>
 
vue.component('child', {
   template: '<div>
          <p>hello</p>
          <slot>默认内容</slot>
        </div>'
})

使用插槽添加header和footer,使用‘具名插槽',也就是给插槽起个名字,各找各的位置。此处也可以写默认值,如果父组件没有对应的插槽内容的话,会显示子组件定义的插槽的默认值。

<div id="app">
  <body-content>
    <div class="header" slot="header">header</div>
    <div class="footer" slot="footer">footer</div>
  </body-content>
</div>
 
vue.component('body-content', {
  template: '<div>
         <slot name="header">default header</slot>
         <div class="content">content</div>
         <slot name="footer">default footer</slot>
        </div>'
})

感兴趣的朋友可以使用在线html/css/javascript代码运行工具:测试上述代码运行效果。

希望本文所述对大家vue.js程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网