javascript - 为什么在 this.$scopedSlots 中也可以使用 Vue 常规插槽?

标签 javascript vue.js vuejs2 vue-component vuejs3

请看这个最小的例子
测试.vue

<template>
  <div>
    <slot name="this_is_not_scoped_slots"/>
  </div>
</template>

<script >
import Vue from "vue";

export default Vue.extend({
  mounted() {
    console.log(Object.keys(this.$scopedSlots));
  }
});
</script>
应用程序.vue
<template>
  <Test>
    <template #this_is_not_scoped_slots>But it shows in this.$scopedSlots</template>
  </Test>
</template>

<script>
import Test from "./Test.vue";

export default {
  components: {
    Test
  }
};
</script>
在上面的示例中,此控制台将注销 ["this_is_not_scoped_slots"] .
为什么会这样?
Vue实例中有两个属性
  • this.$slots
  • this.$scopedSlots

  • 这两者的行为真的不同:
  • 如果您使用 v-slot:my_scope_name="{ someValue }" ,然后 my_scope_name不会出现在 this.$slots
  • 但是,无论您定义什么,您的命名槽将始终显示在 this.$scopedSlots 中。

  • 为什么会这样?
    我正在构建一个库,如果用户提供了命名插槽,我想条件渲染,我应该总是使用 this.$scopedSlots检测那些东西?

    最佳答案

    根据official API :

    1. ....
    2. All $slots are now also exposed on $scopedSlots as functions. If you work with render functions, it is now recommended to always access slots via $scopedSlots, whether they currently use a scope or not. This will not only make future refactors to add a scope simpler, but also ease your eventual migration to Vue 3, where all slots will be functions.

    关于javascript - 为什么在 this.$scopedSlots 中也可以使用 Vue 常规插槽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63756681/

    相关文章:

    javascript - 使用 select2 将 php 数组转换为 javascript 数组

    javascript - 通过 HTML 打开的 PDF 文件的大小

    javascript - Vue基础问题: Integrating fullpage. js wrapper with other behaviors

    css - 验证 : fit v-image within the screen size

    vue.js - Vuejs : Event on route change

    css - VueJS 动态控制 CSS

    javascript - jquery点击滚动特定距离

    javascript - 使用javascript动态输入框折扣计算

    javascript - Vue.js。使用事件总线和存储哪个更好?

    css - 使用 Transition 在 Vuejs 中的 v-if 上设置动画高度