Vue组件按钮disabled属性设置错误及重复键问题求助
问题1:disabled属性类型错误的解决方法
错误根源有两个:
- 你给
disabled传了字符串'isDigitizePolygonDisabled',但Vue要求disabled必须是布尔值类型(或可转换为布尔值的类型); - 你同时在
props和data里声明了同名变量,造成变量冲突。
正确修改方式:
- 删除
data里的重复声明,props定义的属性可直接在模板使用; - 用
v-bind的简写:disabled绑定props中的布尔变量,而非传字符串。
修正后的代码:
<template> <button id="idDigitizePolygonBtn" class="digitizePolygonBtn" :disabled="isDigitizePolygonDisabled"> <slot></slot> </button> </template> <script lang="ts"> export default { props: { isDigitizePolygonDisabled: { type: Boolean, required: true } } } </script>
问题2:重复key错误的解决方法
错误原因:Vue 3中props会自动暴露给模板使用,你在setup里手动返回了和props同名的变量,导致变量名重复。
解决方法:直接删除setup里的返回逻辑,模板可直接引用props中的变量。
修正后的代码:
<template> <button id="idDigitizePolygonBtn" class="clsDigitizePolygonBtn" :disabled="isDigitizePolygonBtnDisabled"> <slot></slot> </button> </template> <script lang="ts"> import { defineComponent } from 'vue' export default defineComponent({ props: { isDigitizePolygonBtnDisabled: { type: Boolean, required: true, }, }, }); </script>
注:required: true和default同时存在是冗余的——当required设为true时,父组件必须传递该属性,default不会生效,所以可以删掉default: false。
内容的提问来源于stack exchange,提问作者Amrmsmb
相关产品推荐
相关产品推荐

