15

我想从字典中设置一个默认属性,如下所示:

  props: {
    title: {
      type: String,
      default: this.$t("basic.confirm"),
    },
    description: {
      type: String,
    }
  }, ...

$t是一个vue-i18n,如果它没有在父类中定义,我想从字典中设置我的标题。但我得到了错误:

未捕获的类型错误:this.$t 不是函数

类似的错误如果我重新加载没有this.

未捕获的 ReferenceError:$t 未定义

但是如果我在 mount 方法中注销这个值,它会很好地工作。

是否有从字典中设置默认属性的解决方案?

提前致谢!

4

2 回答 2

28

一种解决方案是将密钥或其一部分作为默认道具,例如

title: {
   type: String,
   default: "basic.confirm", //or "confirm"
 },

在模板中:

<h1>{{ $t(title) }}</h1> //or $t("basic." + title)

编辑:您可以访问 $t 内部函数

title: {
  type: String,
  default: function () {
    return this.$t("basic.confirm")
  }
},
于 2018-11-06T11:45:53.847 回答
-1

一种解决方案是将密钥或其一部分作为默认道具,例如

 title: {
   type: String,
   default: "", 
 },

在模板中:

    <h1>{{ $t(titlep) }}</h1>

并在脚本中:

    import { useI18n } from 'vue-i18n'
    ...
    setup(props) {
      const { t }  = useI18n()
      const titlep = computed(() =>
        props.title ? props.title : t('basic.confirm')
      )
      return { titlep }
    }
于 2021-08-22T03:18:11.683 回答