如何使用vue中slot在子组件显示父组件传递的模板

小编给大家分享一下如何使用vue中slot在子组件显示父组件传递的模板,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

父组件使用没有指定slot属性,默认为default

在slot中可以使用默认值,如果父组件没有传递对应的slot,则会显示默认值

如何使用vue中slot在子组件显示父组件传递的模板

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="vue.js" charset="utf-8"></script>
</head>
<body>
  <div id="app">
    <modal>
      <!-- 调用父组件的方法 -->
      <h2 @click='click'>aaa</h2></modal>
    <modal>
      <h3>bbb</h3></modal>
    <modal>
      <!-- 使用slot设置模板中的名字,会插入到指定的slot中 -->
      <p slot='title'>hello</p>
      <p slot='content'>
        world
      </p>
    </modal>
    <modal></modal>
  </div>
  <template id="modal">
    <!-- 使用slot在子组件中显示父组件传过来的模板 -->
      <div>
        modal
        <slot name='default'>如果没有会使用这个默认值</slot>
      <h2>
        title:
        <slot name='title'>
        </slot>
      </h2>
      content:
      <slot name='content'></slot>
      </div>
    </template>
  <script type="text/javascript">
    let modal = {
      template: '#modal'
    }
    new Vue({
      el: '#app',
      components: {
        // es 简写 ,只写一个的意思为
        // modal:modal
        modal
      },
      methods: {
        click() {
          console.log('aaa')
        }
      }
    })
  </script>
</body>
</html>

以上是“如何使用vue中slot在子组件显示父组件传递的模板”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!