vue给子组件增加html内容(称为插槽 slot)

插槽给子组件增加内容,插槽可以设置默认值

在子组件中template中插槽写法 <slot></slot>

slot标签内可以添加name属性,要与html中的slot值对应起来

(要是子组件html之间没有写内容,又想显示某个值,可以使用slot默认值:<slot>默认值</slot>)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>插槽 slot</title>
    <script src="./vue.js"></script>
  </head>
  <body>
    <div id="app">
      <body-content>
        <div slot="header">header</div>
        <div slot="footer">footer</div>
      </body-content>
    </div>
    <script>
      Vue.component("bodyContent",{
        template:`<div>
                    <slot name='header'></slot>
                    <div>content</div>
                    <slot name='footer'></slot>
                  </div>`
      });
      var app = new Vue({
        el:'#app'
      })
    </script>
  </body>
</html>

 

作用域插槽

作用域插槽必须是一个以template开头和结尾的内容

插槽要声明从子组件接受的数据是放到slot-scope的值中

<div id="app">
      <child>
        <template>
          <li slot-scope="props">{{props.item}}</li>
        </template>
      </child>
    </div>
    <script>
      Vue.component("child",{
        data:function(){
          return {
            list:[1,2,3,4]
          }
        },
        template:`<div>
                    <ul>
                      <slot v-for="item in list" :item=item></slot>
                    </ul>
                  </div>`
      });
      var app = new Vue({
        el:'#app'
      })
    </script>

 

posted on 2019-07-10 22:29  崭新开始  阅读(7442)  评论(0编辑  收藏  举报