I am using i18n library in Vue.js for language translation. I want to to import in it my script and store a value in data, but I have trouble with importing it. How should I import it? I tried with import $t from "./i18n"; but that just returns this error: Module not found: Error: Can't resolve './i18n'
here is my code:
script>
import Header from "../components/Header";
import $ from "jquery";
import $t from "./i18n";
export default {
name: "GroupPermissions",
components: {
Header
},
data() {
return {
showAddGroupDialog: false,
updatePermissionDialog: false,
itemsToBeDeleted: [],
permissions: $t("groupPermissions.table.permissions")
};
and my main.js:
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import "bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import VueMaterial from "vue-material";
import "vue-material/dist/vue-material.min.css";
import "vue-material/dist/theme/default.css";
import "vue-multiselect/dist/vue-multiselect.min.css";
import $ from "jquery";
import Multiselect from "vue-multiselect";
import i18n from "./i18n";
import "#/plugins/echarts";
import Sticky from 'vue-sticky-directive'
Vue.component("multiselect", Multiselect);
Vue.use(VueMaterial);
Vue.use(Sticky);
Vue.config.productionTip = false;
new Vue({
router,
$,
i18n,
render: h => h(App)
}).$mount("#app");
If you'd like use vue-i18n, in your main.js you should import vue-i18n library first and create an i18n variable like this:
import VueI18n from 'vue-i18n';
const i18n = new VueI18n({
locale: 'en',
messages: { 'en': { title: 'Title' }},
});
and pass the i18n var to your Vue in main.js as you did it:
new Vue({
router,
$,
i18n,
render: h => h(App)
}).$mount("#app");
After this, in your component you will have a this.$t('title') method that will return with 'Title' value.
This link may help for you: http://kazupon.github.io/vue-i18n/started.html#javascript
Imre showed how to install the vue-i18n globally. I'll just add that you can also import an instance of i18n and use it in any javascript file, not only within Vue components.
If you export i18n like this
import VueI18n from 'vue-i18n';
export const i18n = new VueI18n({
locale: 'en',
messages: { 'en': { title: 'Title' }},
});
you can then use it in Vue components, though using this.$t() is preferable.
<script>
import Header from "../components/Header";
import $ from "jquery";
import { i18n } from "./i18n";
export default {
name: "GroupPermissions",
components: {
Header
},
data() {
return {
showAddGroupDialog: false,
updatePermissionDialog: false,
itemsToBeDeleted: [],
permissions: i18n.t("groupPermissions.table.permissions")
};
</script>
But more relevantly, you can use this anywhere else.
//some-function.js
import { i18n } from "./i18n";
function someFunction() {
console.log(i18n.t(...));
}
Related
I am migrating my Vue.js project to the TypeScript.
I found problem during component registration. My code looks like below:
import {Vue, Component} from 'vue-property-decorator'
import ScheduleCard from '../ScheduleCard/ScheduleCard.vue'
#Component({
components: {
ScheduleCard
}
})
export default class ScheduleCanvas extends Vue {
get userSchedule() {
return this.$store.state.userSchedule;
}
addUserSchedule() {
this.$store.dispatch('prepareAndAddUserSchedule');
}
}
When I am trying to import this component and use in another I receiver an error that this component cannot be found.
Adding Vue.component('schedule-canvas', ScheduleCanvas) on the end of the .ts file did the job, but why I have to add this? As far as I know this should work without this line. Could everyone let me know why is that and what could be wrong?
UPDATE: Below code of the parent Component
import {Vue, Component} from 'vue-property-decorator'
import App from './App.vue'
import vuetify from './plugins/vuetify'
import store from './store/store'
import ScheduleCanvas from './components/ScheduleCanvas/ScheduleCanvas.vue'
#Component({
components: {
ScheduleCanvas
}
})
export default class Application extends Vue { }
new Vue({
el: '#app',
vuetify,
store,
render: h => h(App)
})
TypeScript basically has been set in my Webpack-project, and I have working multiple TypeScript file. Also, in .ts files, vue-property-decorator library woks too.
When I tried to rewrite below code in Application.vue to TypeScript, I got error
Error: Could not find file: 'C:\...\development\1_Source\3_admin\3_scripts\Application.vue'.
Application.vue before (works):
<script>
export default {
data() {
return {
navigationDrawerOpened: false
}
}
}
</script>
Application.vue after (has error):
<script lang="ts">
import { Vue, Component} from "vue-property-decorator";
#Component
export default class Application extends Vue {
private navigationDrawerOpened: boolean = false;
}
</script>
App.ts (Application entry point)
import Vue from 'vue';
import Vuetify from 'vuetify';
import Application from './Application.vue';
import router from './router/router';
Vue.use(Vuetify);
new Vue({
el: '#application',
router,
components: { Application },
template: '<Application/>'
});
I'd like to check if the user is validated before entering routes. I'm using vue-router's beforeEach to tackle this. But I realize that I can check the vuex store before the vue instance is initialized.
Main.js
import Vue from "vue";
import Vuetify from 'vuetify';
import Vuex from 'vuex';
import VueRouter from 'vue-router';
import VeeValidate from 'vee-validate';
import store from '../store/store.js';
import App from '../app.vue';
import axios from 'axios';
import progressBar from '../plugins/progress-bar';
import { routes } from '../router-config';
import { sync } from 'vuex-router-sync';
import 'vuetify/dist/vuetify.min.css'
Vue.use(VeeValidate)
Vue.use(VueRouter)
Vue.use(Vuetify)
Vue.use(Vuex)
Vue.config.productionTip = false
axios.defaults.headers.common['Accept'] = 'application/json'
document.addEventListener('DOMContentLoaded', () => {
document.body.appendChild(document.createElement('app'))
const router = new VueRouter({
routes,
mode: 'hash',
saveScrollPosition: true,
});
sync(store, router)
router.beforeEach((to, from, next) => {
debugger;
if (to.meta.requiresAuth && store.getters.isLoggedIn) {
next({ path: '/' })
} else if (to.path === "/") {
next({ path: '/dashboard'})
} else {
next()
}
});
const app = new Vue({
el: 'app',
router,
store,
axios,
render: h => h(App),
template: '<App/>',
components: {
App,
}
});
})
How can I access this so that I can do something like this this.$store.getters.isLoggedIn? Am I thinking of this the right way?
You don't need this.$store. You have store. Just use store.
store.getters.isLoggedIn
this.$store is just a reference to store that you can use inside Vue components. But anywhere you import the store you have access to everything you need.
I cant't figure out why I am getting this error. Everything looks properly.
Import store to the component like this.
import store from './store';
new Vue({
components: {
SomeComponent
},
store
});
My store looks like this
import Vue from 'vue';
import Vuex from 'vuex';
import * as getters from './getters';
import * as actions from './actions';
import mutations from './mutations';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
something
}
})
Please any help.
Thanks
Uncaught Error: [vuex] must call Vue.use(Vuex) before creating a store instance.
Using Vue CLI and setting up like this works for me
in store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
something: ['something']
}
})
in main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
I've had a similar problem, and turns out that my modules were returning a Vuex.Store instance instead of a javascript object.
My files was like:
app.js
import Vue from 'vue'
...
import store from './store'
...
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import myModule from './my-module'
...
export default new Vuex.Store({
modules: { myModule }
....
})
my-module/index.js (Here was my problem)
import Vuex from 'vuex'
...
export default new Vuex.Store({
namespaced: true,
state: { ... },
...
})
My mistake was that I must have only one store, the root store, the others are modules of root. So I must not instantiate a new store, but return a config object instead. Like so:
my-module/index.js (Corrected version)
...
export default {
namespaced: true,
state: { ... },
...
}
So, if anyone arrived here with the same problem, I hope it can save you some time.
See https://github.com/vuejs/vuex/tree/dev/examples/shopping-cart for how they do it in their sample app.
app.js
import 'babel-polyfill'
import Vue from 'vue'
import App from './components/App.vue'
import store from './store'
import { currency } from './currency'
Vue.filter('currency', currency)
new Vue({
el: '#app',
store,
render: h => h(App)
})
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import * as actions from './actions'
import * as getters from './getters'
import cart from './modules/cart'
import products from './modules/products'
import createLogger from '../../../src/plugins/logger'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
actions,
getters,
modules: {
cart,
products
},
strict: debug,
plugins: debug ? [createLogger()] : []
})
#katieh
Ou.. I'e resolved this problem. I had 'vue' instead of 'vue-loader' in webpack. So, *** happens then i remove vue-loader work well
you literally need to add something to the store; a state, module or a getter
I create a repositorie: vue-use-vuex to solved this bug.
You can Use it to fixed:
npm install vue-use-vuex --save
add one line code in you entry:
import 'vue-use-vuex'
The error will not be seen.
im using the Webpack CLI Template.
Then i install https://kazupon.github.io/vue-i18n/ with npm install --save vue-i18n
In my main.js i do the import and set the "en" locale
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import App from './App'
import router from './router'
Vue.use(VueI18n)
Vue.locale('en', {})
new Vue({
el: '.nwt-mm-app',
router,
template: '<App/>',
components: { App }
})
The console output always says
Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_0_vue___default.a.locale is not a function
at eval (eval at <anonymous> (app.js:802), <anonymous>:16:45)
at Object.<anonymous> (app.js:802)
at __webpack_require__ (app.js:660)
at fn (app.js:84)
at Object.<anonymous> (app.js:1176)
at __webpack_require__ (app.js:660)
at app.js:709
at app.js:712
Am i missing somewhat ?
Greetings,
Markus
Well, You can check the author's another repo.
https://github.com/kazupon/vue-i18n-alpha-repro
In the demo, the vue-i18n is like:
import Vue from 'vue'
import App from './App'
import VueI18n from 'vue-i18n'
import router from './router'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'ja',
messages: {
ja: {
hello: 'こんにちは'
},
en: {
hello: 'hello'
}
}
})
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
i18n,
template: '<App/>',
components: { App }
})
And it works.
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
// console.log(navigator.language);
let defaultLang = "zh"
const i18n = new VueI18n({
locale: defaultLang,//默认语言
messages: {
zh:{
hello:'你好',
footTitle:['现货交易','采购供应','行情资讯','个人中心']
},
en: {
hello: 'hello',
footTitle:['Spot Trading','Purchase & Supply','Market Information','Personal Center']
},
}
})
export default i18n