vue插槽slot(加深印象)

根据的都是更新后的2.6新版本

概念:

组件预留的html模板区域,这块模板显示不显示怎样显示由父组件决定

插槽作用域

父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。

案例分析

父组件
<template>
  <div id="app">
    <h1>vue自定义插槽父组件</h1>
    <children-slot>
      <!-- <template v-slot:header> -->
      <!-- 缩写 -->
      <template #header>
        <h4>这是在父组件的要显示在子组件的header</h4>
      </template>

      <p>这是在父组件的要显示在子组件的content</p>
      <p>这是在父组件的要显示在子组件的content2</p>

      <template v-slot:footer="footerProps">
        <p>这是在父组件的要显示在子组件的footer</p>
        <!-- 此处可得到子组件定义的childrenObj的值 -->
        <p>我是访问子组件定义的值{{ footerProps.childrenObj.lastname }}</p>
      </template>
    </children-slot>
    <!-- 只有匿名卡槽才能省略写template -->
    <!-- 写法1 -->
    <!-- <single-slot v-slot="singleProps">
      <template>
        <p>我是访问单独插卡槽的值:{{ singleProps.info.last }}</p>
      </template>
    </single-slot> -->
    <single-slot v-slot="{ info }">
      <template>
        <p>我是访问单独插卡槽的值:{{ info.last }}</p>
      </template>
    </single-slot>
  </div>
</template>
<script>
import ChildrenSlot from "@/components/ChildrenSlot.vue";
import SingleSlot from "@/components/SingleSlot.vue";
export default {
  name: "App",
  components: {
    ChildrenSlot,
    SingleSlot,
  },
  data() {
    return {};
  },
};
</script>

子组件ChildrenSlot
<template>
  <div id="app">
    <h3>vue自定义插槽子组件包含多个</h3>
    <p>具名卡槽header</p>

    <slot name="header"></slot>
    <!-- <slot></slot> -->
    <p>具名卡槽footer</p>
    <slot name="footer" v-bind:childrenObj="childrenObj">
      <!-- 后备内容默认值 -->
      当footer卡槽没有值时候,我是默认:{{ childrenObj.firstname }}
    </slot>
  </div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      childrenObj: {
        firstname: "wht",
        lastname: "thw",
      },
    };
  },
};
</script>

SingleSlot
<template>
  <div>
    <h4>单个匿名卡槽</h4>
    <!-- 作用域插槽   绑定在 <slot> 元素上的 attribute 被称为插槽 prop。-->
    <!-- 现在在父级作用域中,我们可以使用带值的 v-slot 来定义我们提供的插槽 prop 的名字 -->
    <slot :info="info">
      <!-- 后备内容默认值 -->
      当没有的时候,我是单个卡槽默认值{{ info.first }}
    </slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      info: {
        first: "匿名卡槽默认值",
        last: "匿名卡槽真实值",
      },
    };
  },
};
</script>
<style></style>

展示界面的最终效果

WX20210520-143431@2x.png

原文地址:https://www.cnblogs.com/hanhaiyuntao/p/14790153.html