如何在不使用道具的 "default" 属性 的情况下传递具有默认值的道具以防道具为空

How to pass a prop with a default value in case the prop is empty without using the prop's "default" property

我正在使用 third party multi-language package,其中翻译值只能 obtained/used 来自组件的模板,而不是来自组件的逻辑(至少我找不到后者的方法)。

我需要在某些组件中将这样的翻译值作为默认属性值传递:

:placeholder="{ propValue ? propValue : $t('value') }

如果明确指定了占位符,则使用它。如果不是,请改用 $t('value') 。正确的写法是什么?

我尝试这样做是为了回应@Michael 的回答:

import i18n from "@/utilities/i18n";
export default {
  data() {
    return {
      test: i18n.t('register.agreeTermsCaptionLink')
    };
  }
};

出现此错误:

_utilities_i18n__WEBPACK_IMPORTED_MODULE_7__.default.t is not a function

您可以像这样设置属性的默认值:

props: {
     propValue: {
         type: String,
         default: this.$t('value')
     }
}

在您的模板中,您只需分配该值,例如::placeholder="propValue"

这就是你要达到的目标吗?

祝你好运!

解决方案 1

只需从 prop 表达式中删除括号::placeholder="propValue ? propValue : $t('value')"

解决方案 2

更复杂但有助于保持模板更简洁...

where translation values can only be obtained/used from component's template, not from component's logic

有了 vue-i18n,您当然可以通过使用 $t 函数直接在代码中获取翻译,注入到您的组件实例中,如下所示:this.$t('key.to.translation')

唯一的问题是,这不可能用于初始化道具默认值,因为 this 在那里不可用。

$t实际上只是VueI18n全局对象的returns实例函数。因此,如果您像这样设置 VueI18n:

import Vue from "vue";
import VueI18n from "vue-i18n";

Vue.use(VueI18n);

const messages = {
  en: {
    messages: {
      placeholder: "Placeholder"
    }
  },
  cz: {
    messages: {
      placeholder: "Zástupný symbol :)"
    }
  }
};

export default new VueI18n({
  locale: "en",
  messages
});

您可以这样做以提供翻译作为您的道具的默认值:

import i18n from "../i18n";

export default {
  name: "HelloWorld",
  props: {
    placeholder: {
      type: String,
      // default: this.$t("value") - Wont work as `this` is not Vue instance
      default: i18n.t("messages.placeholder")
    }
  }
};

Demo