我正在做VueCLI。我已经创建了包含输入规则的.js文件:
import Vue from 'vue'
export const $t = (sign) => Vue.prototype.$t(sign)
function checkMail(email) {
const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/ // eslint-disable-line no-eval
return re.test(String(email).toLowerCase())
}
const rules = {
gdprRequired: (v) => !!v || $t('registerPage.gdprNotChecked'),
emailRules: [(v) => checkMail(v) || $t('registerPage.wrongMail')],
}
export default rules
我想在外部js文件中声明规则,然后在其他vue文件中导入它。当我做这个规则检查值正确,但它不显示翻译错误消息。我尝试了export const $t = (sign) => Vue.prototype.$t(sign)
,因为类似的代码为下一步工作,但在这里,在VueCLI我得到了错误:
vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in beforeMount hook: "ReferenceError: $t is not defined"
found in
---> <VTextField>
<VForm>
<Register>
<VMain>
<VApp>
<Session> at src/layouts/Session/Session.vue
<App> at src/App.vue
<Root>
:
vue.runtime.esm.js?2b0e:1888 ReferenceError: $t is not defined
at rules.emailRules (rules.js?d86d:21)
at VueComponent.validate (index.ts?91bf:254)
at VueComponent.beforeMount (index.ts?91bf:217)
at invokeWithErrorHandling (vue.runtime.esm.js?2b0e:1854)
at callHook (vue.runtime.esm.js?2b0e:4219)
at mountComponent (vue.runtime.esm.js?2b0e:4043)
at VueComponent.Vue.$mount (vue.runtime.esm.js?2b0e:8415)
at init (vue.runtime.esm.js?2b0e:3118)
at createComponent (vue.runtime.esm.js?2b0e:5978)
at createElm (vue.runtime.esm.js?2b0e:5925)
这里导入'register.vue'中的代码:
import rulesConstant from "@/constants/rules";
计算导出的规则到值变量:
computed: {
rules() {
return rulesConstant;
},
},
使用例子:
<v-checkbox
class="custom-checkbox"
:rules="[rules.gdprRequired]"
v-model="gdprCheck"
></v-checkbox>
你能帮我吗?
在Vue组件外使用vue-i18n
最常见的方法是导入VueI18n
类的单例实例并直接使用它:
@/i18n/index.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import locales from './locales'
Vue.use(VueI18n);
export default new VueI18n({
locale: 'en',
messages: locales,
});
@
/常量/规则import i18n from '@/i18n/index.js'
const rules = {
gdprRequired: (v) => !!v || i18n.t('registerPage.gdprNotChecked'),
emailRules: [(v) => checkMail(v) || i18n.t('registerPage.wrongMail')],
}
export default rules
这样您就可以使用所有的实例方法,而不仅仅是t