'Can I use Vue-I18n without a build step?
If I use Vue2 with no build step, is there a way to use Vue-I18n the same way?
<!doctype html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/vue-i18n@8"></script>
</head>
<body>
<div id="vueApp"></div>
<script>
const VueI18n = window.VueI18n;
if (VueI18n) {
const i18n = new VueI18n({
locale: 'en',
messages: {
en: {
hello: 'Hello there!',
}
}
});
Vue.use(i18n);
}
new Vue({
template: '<div><p>This is Vue!</p><p>{{welcome}} and {{hello}}</p></div>',
el: document.querySelector('#vueApp'),
data: function() {
return {
welcome: 'Welcome',
hello: this.$t('hello'),
};
},
});
</script>
</body>
</html>
I hope to see
This is Vue!
Welcome and Hello there!
Instead, the dev console has the message
TypeError: Cannot read properties of undefined (reading '_t')
at Vue.$t (vue-i18n@8:242:19)
at Vue.data (vuei18.html:29:29)
at Vue.mergedInstanceDataFn (vue.js:1240:22)
at getData (vue.js:4758:19)
at initData (vue.js:4715:9)
at initState (vue.js:4654:7)
at Vue._init (vue.js:5014:7)
at new Vue (vue.js:5092:10)
at vuei18.html:23:5
Am I completely out of luck, or is there a way to make this happen?
Thanks for any help.
Solution 1:[1]
this.$t() is the same as t() from the VueI18n instance (i.e., the result of new VueI18n()), so you can use it here:
const VueI18n = window.VueI18n;
let i18n = null
if (VueI18n) {
?
i18n = new VueI18n({?});
Vue.use(i18n);
}
new Vue({
?
data: function() {
return {
welcome: 'Welcome',
?
hello: i18n?.t('hello'),
};
},
});
<head>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/vue-i18n@8"></script>
</head>
<body>
<div id="vueApp"></div>
<script>
const VueI18n = window.VueI18n;
let i18n = null
if (VueI18n) {
i18n = new VueI18n({
locale: 'en',
messages: {
en: {
hello: 'Hello there!',
}
}
});
Vue.use(i18n);
}
new Vue({
template: `<div><p>This is Vue!</p><p>{{welcome}} and {{hello}}</p></div>`,
el: document.querySelector('#vueApp'),
data: function() {
return {
welcome: 'Welcome',
hello: i18n?.t('hello'),
};
},
});
</script>
</body>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tony19 |
