Vue插槽

https://www.jb51.net/article/157356.htm

https://www.jb51.net/article/135748.htm

什么是插槽?

这里的slot标签就是插槽
插槽就是一个坑
插槽可以指定默认数据
插槽可以指定名称 默认叫匿名插槽
插槽可以有多个 有多少个就填充多少个

作用是什么?

将 <slot> 元素作为承载分发内容的出口。

props可以将数据从父组件传入子组件,slot可以将html从父组件传入子组件。

 

 

抄过来的部分代码:-> -> 嘿嘿嘿

<!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">
      <p>===============单个插槽=================</p>

      <h1>我是父组件的标题</h1>
      <my-component>
        <p>这是一些初始内容</p>
        <p>这是更多的初始内容</p>
      </my-component>

      <p>===============具名插槽=================</p>

      <my-component2>
         <h1 slot="header">这里可能是一个页面标题</h1>

         <p>主要内容的一个段落。</p>
         <p>另一个主要段落。</p>

         <p slot="footer">这里有一些联系信息</p>
      </my-component2>

      <p>===============作用域插槽=================</p>
      <!-- 在父级中,具有特殊特性 slot-scope 的 <template> 元素必须存在,表示它是作用域插槽的模板。slot-scope 的值将被用作一个临时变量名,此变量接收从子组件传递过来的 prop 对象: -->
       <child>
        <template scope="props">
         <span>hello from parent</span><br>
         <span>{{ props.text }}</span>
        </template>
      </child>

    </div>
    <script type="text/javascript">

      Vue.component('my-component', {
       // 有效,因为是在正确的作用域内
       template: '<div>\
              <h2>我是子组件的标题</h2>\
              <slot>只有在没有要分发的内容时才会显示。</slot>\
            </div>',
       data: function () {
        return {

        }
       }
      });

      Vue.component('my-component2', {
       // 有效,因为是在正确的作用域内
       template: '<div class="container">\
             <header>\
              <slot name="header"></slot>\
             </header>\
              <main>\
              <slot></slot>\
             </main>\
             <footer>\
              <slot name="footer"></slot>\
             </footer>\
            </div>',
       data: function () {
        return {

        }
       }
      });

      // 在子组件中,只需将数据传递到插槽,就像你将 prop 传递给组件一样:
      Vue.component('child',{
        template:'<ul>' +
              '<slot text="hello from child"></slot>' +
             '</ul>',
        data:function(){
         return {

         }
        },
      })

      new Vue({
        el:'#app',
        data:{
          msg:'你好啊'
        }
      })

    </script>
  </body>
</html>

 

运行效果

 

更多代码示例请见:

https://github.com/nwgdegitHub/vueJS2-learning

posted @ 2020-09-21 17:02  liuw_flexi  阅读(207)  评论(0编辑  收藏  举报