解决:Vue3 - defineProps 设置默认值报错问题

1,问题

使用 defineProps 指定默认值时报错,代码如下:

<template>
	<input type="text" :placeholder="props.placeholder" />
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";

const { t } = useI18n();

interface Props {
	placeholder: string;
}
const props = withDefaults(defineProps<Props>(), {
	placeholder: t("home.title"),
});
</script>

报错信息:

在这里插入图片描述

翻译:

<script setup> 中的 defineProps() 不能引用本地声明的变量,因为它将被提升到 setup() 函数外。如果你的组件选项需要在 module scope(模块作用域)中初始化,可使用单独的 <script> 来导出这些选项。

2,分析

SFC 有2个 scopemodule scopesetup scope

按照报错信息分析:因为在 setup scope 中定义的本地变量会被提升到 module scope。所以 defineProps() 不能引用本地声明的变量。

官方文档 中也有说明,

在这里插入图片描述

测试1

<template>
	<input type="text" :placeholder="props.placeholder" />
</template>

<script setup lang="ts">
interface Props {
	placeholder: string;
}
const a = "1234";
const props = withDefaults(defineProps<Props>(), {
	placeholder: a,
});
</script>

这样定义的本地变量,渲染并没有问题!

测试2,修改代码如下,渲染报错!

const a = () => "1234";
const props = withDefaults(defineProps<Props>(), {
	placeholder: a(),
});

2.1,按报错提示信息测试

所以按照报错提示信息,可使用单独的 <script> 来导出这些选项:

方式1:√

<script lang="ts">
const a = () => "1234";
</script>

<script setup lang="ts">
interface Props {
	placeholder: string;
}

const props = withDefaults(defineProps<Props>(), {
	placeholder: a(),
});
</script>

方式2:√

export const a = () => "1234";
<script setup lang="ts">
import { a } from "./index";
interface Props {
	placeholder: string;
}

const props = withDefaults(defineProps<Props>(), {
	placeholder: a(),
});
</script>

2.2,测试 vue-i18n

<script lang="ts">
import { useI18n } from "vue-i18n";
const { t } = useI18n();
</script>

<script setup lang="ts">
interface Props {
	placeholder: string;
}
const props = withDefaults(defineProps<Props>(), {
	placeholder: t("home.title"),
});
</script>

发现 const { t } = useI18n(); 只能在 setup 中使用:

在这里插入图片描述

但如果在 setup 中使用函数调用的方式,就会报错。

3,解决

所以,使用外部导入的方式来使用 vue-i18n

<template>
	<input type="text" :placeholder="props.placeholder" />
</template>

<script setup lang="ts">
import i18n from "@/i18n";

interface Props {
	placeholder: string;
}
const props = withDefaults(defineProps<Props>(), {
	placeholder: i18n.global.t("home.title"),
});
</script>

以上。

参考1

参考2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

下雪天的夏风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值