我正在使用third party multi-language package,其中只能从组件的模板而不是从组件的逻辑(至少我无法找到后者)来获取/使用转换值。
我需要在某些组件中传递这种转换值作为默认的prop值:
: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不是函数
答案 0 :(得分:0)
只需从prop表达式中删除括号::placeholder="propValue ? propValue : $t('value')"
更复杂,但有助于使模板保持清洁...
其中只能从组件的模板而不是组件的逻辑中获取/使用转换值
使用vue-i18n,您当然可以通过使用注入到组件实例中的$t
函数来直接在代码中获取翻译,例如:this.$t('key.to.translation')
唯一的问题是,这不能用于初始化props的默认值,因为this
在那里不可用。
但是$t
实际上只是返回VueI18n
全局对象的实例函数。因此,如果您这样设置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")
}
}
};
答案 1 :(得分:-1)
您可以像这样将默认值设置为prop:
props: {
propValue: {
type: String,
default: this.$t('value')
}
}
使用该模板中的值,您只需分配以下值即可::placeholder="propValue"
那是您想要达到的目标吗?
祝你好运!