Internal server error: Error parsing JavaScript expression: Unexpected token (1:2)

 Internal server error: Error parsing JavaScript expression: Unexpected token (1:2) 不能将类型“true”分配给类型“Numberish | undefined”。 ts-plugin(2322)

1. 简要解释报错原因

在 <svg :style={ width, height }> 中,width 和 height 是字符串类型,而 :style 需要的是一个对象,其中的属性值应该是 Numberish | undefined 类型。直接使用字符串会导致类型不匹配,因此 TypeScript 抛出错误。

解决方案:刚开始想着可以通过将 width 和 height 转换为 CSS 属性的正确格式,或者使用 :style 的字符串形式来避免类型不匹配的问题。推荐使用 :style 的对象形式,并确保属性值是有效的 CSS 样式值。

<template>
  <div>
    <svg :style="svgStyle">
      <use :xlink:href="prefix + name" :fill="color"></use>
    </svg>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';

defineProps({
  prefix: {
    type: String,
    default: '#icon-'
  },
  name: String,
  color: {
    type: String,
    default: ''
  },
  width: {
    type: String,
    default: '16px'
  },
  height: {
    type: String,
    default: '16px'
  }
});

const svgStyle = computed(() => ({
  width: `${props.width}`,
  height: `${props.height}`
}));
</script>

<style scoped></style>

发现仍然报错 -错误信息: 找不到名称“props”。 ts-plugin(2304)

解决方案:在 <script setup> 中,defineProps 返回的 props 需要通过解构或直接引用 props 对象来访问。当前代码中直接使用了 props.width 和 props.height,但没有正确引入 props 对象,导致 TypeScript 报错。可以通过解构 defineProps 返回的对象或将 defineProps 的返回值赋值给一个变量来正确访问 props。

<template>
  <div>
    <svg :style="svgStyle">
      <use :xlink:href="prefix + name" :fill="color"></use>
    </svg>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';

const props = defineProps({
  prefix: {
    type: String,
    default: '#icon-'
  },
  name: String,
  color: {
    type: String,
    default: ''
  },
  width: {
    type: String,
    default: '16px'
  },
  height: {
    type: String,
    default: '16px'
  }
});

const svgStyle = computed(() => ({
  width: props.width,
  height: props.height
}));
</script>

<style scoped></style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值