MST
星途 面试题库

面试题:Vue插槽优先级在具名插槽和作用域插槽共存时如何体现?

假设一个Vue组件同时使用了具名插槽和作用域插槽,描述它们之间优先级的规则,并编写代码示例展示优先级的实际表现。
33.4万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

优先级规则

在Vue组件中,当同时使用具名插槽和作用域插槽时,作用域插槽的优先级高于具名插槽。如果在同一位置既定义了具名插槽又定义了作用域插槽,作用域插槽会生效,具名插槽会被忽略。

代码示例

  1. 父组件模板
<template>
  <div>
    <my-component>
      <!-- 具名插槽 -->
      <template v-slot:header>
        <h1>这是具名插槽 - 标题</h1>
      </template>
      <!-- 作用域插槽 -->
      <template v-slot:default="scope">
        <p>这是作用域插槽,数据: {{ scope.data }}</p>
      </template>
    </my-component>
  </div>
</template>

<script>
import MyComponent from './MyComponent.vue';

export default {
  components: {
    MyComponent
  }
}
</script>
  1. 子组件 MyComponent.vue 模板
<template>
  <div>
    <slot name="header"></slot>
    <slot :data="componentData"></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      componentData: '来自子组件的数据'
    }
  }
}
</script>

在上述代码中,虽然定义了具名插槽 header,但由于在默认插槽位置同时定义了作用域插槽,最终渲染的是作用域插槽的内容,具名插槽 header 被忽略。如果去掉作用域插槽部分,具名插槽 header 就会正常渲染。