十一、插槽

插槽介绍

  • 插槽是Vue实现了一套内容分发的API。
  • 元素:元素作为承载内容分发的出口
  • 当组件渲染的时候,元素将会替换为你所插入的内容(可以是字符串、HTML、组件)
字符串

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Documenttitle>
head>
<body>
  <div id="app">
    <hello-word>
      世界
    hello-word>
  div>
  
  <template id='hello'>
    <div>
      <span>你好!span>
      <slot>slot>
    div>
  template>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
  <script>
    const HelloWord = {
      template: '#hello'
    }
    new Vue({
      el: '#app',
      components: {
        HelloWord
      }
    })
  script>
body>
html>
HTML
<body>
  <div id="app">
    <hello-word>
      <h1>世界h1>
    hello-word>
  div>
  <template id='hello'>
    <div>
      <span>你好!span>
      <slot>slot>
    div>
  template>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
  <script>
    const HelloWord = {
      template: '#hello'
    }
    new Vue({
      el: '#app',
      components: {
        HelloWord
      }
    })
  script>
body>
组件
<body>
  <div id="app">
    <hello-word>
      <demo-scope>demo-scope>
    hello-word>
  div>
  
  <template id='hello'>
    <div>
      <span>你好!span>
      <slot>slot>
    div>
  template>
  
  <template id='scope'>
    <div>
      你的名字是?
    div>
  template>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
  <script>
    const HelloWord = {
      template: '#hello'
    }
    const DemoScope = {
      template: '#scope'
    }
    new Vue({
      el: '#app',
      components: {
        HelloWord,
        DemoScope
      }
    })
  script>
body>

注意⚠️:如果没有元素,那么组件起始标签到结束标签之间的任何内容都将会被抛弃。

具名插槽

v-slot指令自Vue2.6.0起引入,提供更好的slotslot-scope特性的API代替方案

  • 一个不带name元素会带有隐含的名字‘default’
  • 在向具名插槽提供内容的时候,我们可以在一个