slot插槽

slot插槽

一、作用/概念

预先将将来要使用的内容进行保留

<body>
  <div id="app">
    <Hello>
      <div>
        这里是1903
      </div>
    </Hello>
  </div>
  <template id="hello">
    <div>
      <slot></slot>
      <h3>这里是hello</h3>
    </div>
  </template>
</body>
<script>
  Vue.component('Hello',{
    template: '#hello'
  })

  new Vue({
    el: '#app'
  })
</script>

二、具名插槽 : 给slot起个名字

Vue2.6版本之前的写法(旧):

<body>
  <div id="app">
    <Hello>
      <header slot = 'header'> 这里是头部 </header>
      <footer slot = 'footer'> 这里是底部 </footer>
    </Hello>
  </div>
  <template id="hello">
    <div>
      <slot name = "header"></slot>
      <h3>这里是hello</h3>
      <slot name = "footer"></slot>
    </div>
  </template>
</body>
<script>

  Vue.component('Hello',{
    template: '#hello'
  })

  new Vue({
    el: '#app'
  })
</script>
  • 注意: 以上两种形式在 vue2.6以上被废弃,vue2.6版本后使用的是 v-slot 指令
  • 为什么要 用 v-slot指令来代替呢?
    • 经具名插槽和作用域插槽进行统一
    • 要将这两个属性带有 vue的标志,并且符合vue两个最大的特性之一: 指令的概念

Vue2.6版本之后的写法(新):

<body>
<div id="app">
    <Hello>
      <template v-slot:header>
        <h1>Here might be a page title</h1>
      </template>
    
      <p>A paragraph for the main content.</p>
      <p>And another one.</p>
    
      <template v-slot:footer>
        <p>Here's some contact info</p>
      </template>
    </Hello>
  </div>
  <template id ='hello'>
    <div class="container">
      <header>
        <!-- 我们希望把页头放这里 -->
        <slot name = "header"></slot>
      </header>
      <main>
        <!-- 我们希望把主要内容放这里 -->
      </main>
      <footer>
        <!-- 我们希望把页脚放这里 -->
        <slot name = 'footer'></slot>
      </footer>
    </div>
  </template>
</body>
<script>

  Vue.component('Hello',{
    template: '#hello'
  })

  new Vue({
    el: '#app',
    data: {
      msg: '<h3> hello 1903</h3>'
    }
  })
</script>

三、作用域插槽

1.旧: slot-scope

  • 使用流程
    • 在组件的模板中书写slot插槽,并将当前组件的数据通过 v-bind 绑定在 slot标签上
    • 在组件使用时,通过slot-scope = “slotProp” 来接收slot标签身上绑定的数据
    • 通过 slotProp.xxx 就可以进行使用了
<body>
  <div id="app">
    <Hello>
      <template slot = "default" slot-scope = "slotProp">
        <p> {{ slotProp.msg }} </p>
      </template>
    </Hello>
  </div>
  <template id="hello">
    <div>
      <slot name = "default" :msg = "msg"></slot>
    </div>
  </template>
</body>
<script>
  Vue.component('Hello',{
    template: '#hello',
    data () {
      return {
        msg: 'hello'
      }
    }
  })
  new Vue({
    el: '#app'
  })
</script>

2.新:v-slot

<body>
  <div id="app">
    <Hello>
      <template v-slot:default = "slotProp">
        {{ slotProp.msg }}
      </template>
    </Hello>
  </div>
  <template id="hello">
    <div>
      <slot name = "default" :msg = "msg"></slot>
    </div>
  </template>
</body>
<script>

  new Vue({
    components: {
      'Hello': {
        template: '#hello',
        data () {
          return {
            msg: 'hello'
          }
        }
      }
    }
  }).$mount('#app')
</script>

猜你喜欢

转载自blog.csdn.net/huhu_nihao/article/details/93785664