Vue 去哪儿学习笔记(第四章 3.使用插槽)

101 阅读1分钟

slot使用

// 具名插槽
  <div id="root">
    <child content="Dell" ></child>
    <child content="Lee" ></child>
  </div>
  <script>
    Vue.component('child',{
      props: {
        content: String
      },
      // 具名插槽
      template: `<div @click="handleClick" >
        <slot name="header" ></slot> 
        <div class='content' >content</div>
        <slot name="footer" ></slot> 
        </div>`,
      methods: {
        handleClick: function(){
          this.bus.$emit('change', { content: this.content })
        }
      },
      })
          let vm = new Vue({
      el: '#root'
    })
  </script>

作用域插槽

vue作用域插槽官方教程

让插槽可访问子组件中才有的数据,例如下面代码中的user

<current-user>
  {{ user.firstName }}
</current-user>

为了让user在父级的插槽内容中可用,我们可将user作为<slot>元素的一个attribute绑定上去

<span>
    <slot v-bind:user="user >
        {{ user.lastName }}
    </slot>
</span>

绑定在slot元素上的attribute被称为插槽prop,在父级作用域中,我们可使用带值的v-slot定义我们提供的插槽prop名字

<current-user>
    <template v-slot:default="slotProps">
        {{ slotProps.user.firstName }}
    </template>
</current-user>

外层使用时必须套template

动态组件

会根据type类型展示不同的组件,type为组件名字,如果组件加上v-once,则 只会渲染一次,后面数据改变也不会重新渲染。包括子组件也不会重新渲染

<component :is="type" ></component>