Vue3+Vuetify中ESLint提示props已在上级作用域声明的解决办法
解决Vue 3 + Vuetify中vue/no-template-shadow规则警告的方法
你遇到的警告源于模板中插槽激活器解构的props变量,与<script setup>里通过defineProps声明的组件props变量重名,触发了ESLint的vue/no-template-shadow规则(禁止模板变量遮蔽上层作用域的变量)。以下是两种无需忽略警告的合理解决方法:
方案1:重命名插槽的props变量(推荐)
直接给插槽解构的props换个别名,避免和组件的props冲突,修改量最小且不影响原有逻辑:
<template> <v-tooltip location="bottom" :text="tooltipText"> <!-- 将插槽的props重命名为activatorProps --> <template #activator="{ props: activatorProps }"> <v-btn-icon-secondary v-bind="activatorProps" :icon="icon" :color="color" @click="handleClick" > </v-btn-icon-secondary> </template> </v-tooltip> </template> <script setup> import { computed } from "vue"; const props = defineProps({ tooltipText: { type: String, required: false, default: "" }, icon: { type: String, required: false, default: "mdi-card" }, color: { type: String, required: false, default: "primary" }, }); const emit = defineEmits(["click"]); function handleClick(event) { emit("click", event); } </script>
方案2:重命名组件的props变量
如果希望保留模板中插槽的props命名,可以修改<script setup>里defineProps返回的变量名,同时调整模板中对组件props的引用:
<template> <v-tooltip location="bottom" :text="componentProps.tooltipText"> <template #activator="{ props }"> <v-btn-icon-secondary v-bind="props" :icon="componentProps.icon" :color="componentProps.color" @click="handleClick" > </v-btn-icon-secondary> </template> </v-tooltip> </template> <script setup> import { computed } from "vue"; // 将组件props重命名为componentProps const componentProps = defineProps({ tooltipText: { type: String, required: false, default: "" }, icon: { type: String, required: false, default: "mdi-card" }, color: { type: String, required: false, default: "primary" }, }); const emit = defineEmits(["click"]); function handleClick(event) { emit("click", event); } </script>
两种方案都能有效解决警告,其中方案1因修改范围更小、逻辑更直观,是更推荐的选择。
内容的提问来源于stack exchange,提问作者Otto Paulsen
相关产品推荐
相关产品推荐

