如何在defineProps中设置本地默认值?

问题描述 投票:0回答:2

我尝试使用

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>

处理这个问题的最佳方法是什么?

internationalization vuejs3
2个回答
21
投票

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


21
投票

如何定义默认的 props

首先,如果您希望在使用类型声明时使用默认 props 值,请使用以下命令:

export interface Props {
  msg?: string
  labels?: string[]
}

const props = withDefaults(defineProps<Props>(), {
  msg: 'hello',
  labels: () => ['one', 'two']
})

阅读此问题

了解更多这里

如何使用默认值定义 props(引用本地声明的变量)

有几种解决方案,第一种是导入 i18n 直接使用

import { useI18n } from 'vue-i18n'

const props = withDefaults(defineProps<{ test?: string }>(), {
  test: () => useI18n().t('test')
})
© www.soinside.com 2019 - 2024. All rights reserved.