0
点赞
收藏
分享

微信扫一扫

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

i奇异 2024-09-17 阅读 23

目录

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>

报错信息:

在这里插入图片描述

翻译:

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

举报

相关推荐

0 条评论