我尝试使用
i18n
将 prop 的默认值设置为本地值。我正在使用 Vue 3.2 和脚本设置标签。
我尝试了以下方法,但这给了我一个错误:
defineProps 引用本地声明的变量。
<script setup>
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
defineProps({
type: { type: String, required: true },
title: { type: String, required: false, default: `${t('oops', 1)} ${t('request_error', 1)}` },
description: { type: String, required: false, default: '' },
showReload: { type: Boolean, required: false, default: false },
error: { type: String, required: true },
});
</script>
处理这个问题的最佳方法是什么?
defineProps
是一个编译器宏,因此您不能在其中使用任何运行时值。我建议使用局部变量作为默认值:
<script setup>
import { useI18n } from 'vue-i18n';
const props = defineProps({
type: { type: String, required: true },
title: { type: String, required: false},
description: { type: String, required: false, default: '' },
showReload: { type: Boolean, required: false, default: false },
error: { type: String, required: true },
});
const { t } = useI18n();
const titleWithDefault = props.title || `${t('oops', 1)} ${t('request_error', 1)}`;
</script>
在最后一个要点中也进行了描述:https://v3.vuejs.org/api/sfc-script-setup.html#defineprops-and-defineemits
首先,如果您希望在使用类型声明时使用默认 props 值,请使用以下命令:
export interface Props {
msg?: string
labels?: string[]
}
const props = withDefaults(defineProps<Props>(), {
msg: 'hello',
labels: () => ['one', 'two']
})
阅读此问题
了解更多这里
有几种解决方案,第一种是导入 i18n 直接使用
import { useI18n } from 'vue-i18n'
const props = withDefaults(defineProps<{ test?: string }>(), {
test: () => useI18n().t('test')
})