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

Tho*_*ore 16 internationalization vuejs3

我尝试使用 将 prop 的默认值设置为本地值i18n。我正在使用 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>
Run Code Online (Sandbox Code Playgroud)

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

sad*_*adi 24

如何使用默认值定义 props

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

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

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

Run Code Online (Sandbox Code Playgroud)

阅读这个问题

在这里了解更多

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

解决办法是导入i18n直接使用

import { useI18n } from 'vue-i18n'


export interface Props {
  msg?: string
}

const props = withDefaults(defineProps<Props>(), {
  msg: () => useI18n().t('message')
})
Run Code Online (Sandbox Code Playgroud)

在此解决方案中,您不会失去反应性


Tho*_*mas 22

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>
Run Code Online (Sandbox Code Playgroud)

在最后一个要点中也进行了描述:https://v3.vuejs.org/api/sfc-script-setup.html#defineprops-and-defineemits

  • 我迟到了讨论。我喜欢你的解决方案,@Thomas,但如果 title 属性发生变化,它会在“titleWithDefault”中被忽视。使用“计算”​​将有助于保持其反应性。 (2认同)