i want to get my current locale , because i need to check if the current locale === 'en' then return true or false, how can i do this? Vue.js/i18n/vee-validate
main.js :
import { createApp } from "vue";
import { createPinia } from "pinia";
import "./index.css";
import App from "./App.vue";
import router from "./router";
import "#/config/vee-validate/rules";
import "#/config/vee-validate/messages";
const app = createApp(App);
app.use(createPinia());
app.use(router);
app.mount("#app");
In option API use :
this.$i18n.locale
in composition API use the useI18n function to get the locale :
const {locale}=useI18n()
Related
I tried to upgrade one of my apps from Vue 2 to Vue 3.
Unfortunately I can't use: Vue.use() function.
For example my code in Vue 2:
import Vue from 'vue'
import App from './App.vue'
import store from './store'
import router from './router'
import VueCookie from 'vue-cookie'
Vue.use(VueCookie);
new Vue({
store,
router,
render: h => h(App)
}).$mount('#app')
Same in Vue 3:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { store } from './store'
import VueCookie from 'vue-cookie'
//Vue.use(VueCookie); //old line in vue 2
createApp.use('VueCookie'); //this is not works and return error
createApp(App).use(router,store).mount('#app') //Is this line correct?
What am I missing here?
Try like following, first define app then use it:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import VueCookie from 'vue-cookie'
const app = createApp(App);
app.use(router);
app.use(store);
app.use(VueCookie);
app.mount('#app')
You can use it like:
import VueCookie from 'vue-cookie'
VueCookie.set("mycookie", "value", "1h")
I have a project where I need to do translations inside the Vuex store. But I keep on getting an error when trying to translate using i18n inside the store.
I have tried to import and instance of i18n inside the store using the following import statement. But I then I get an error Uncaught TypeError: _i18n__WEBPACK_IMPORTED_MODULE_3__.default.t is not a function
import i18n from '#/i18n';
In the main.js file of my Vue project I import and use the i18n file:
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { store } from './store';
import i18n from './i18n';
createApp(App).use(i18n).use(store).use(router).mount('#app');
This is my i18n.js file that is located inside the src folder:
import { createI18n } from 'vue-i18n';
function loadLocaleMessages() {
const locales = require.context(
'./locales',
true,
/[A-Za-z0-9-_,\s]+\.json$/i
);
const messages = {};
locales.keys().forEach((key) => {
const matched = key.match(/([A-Za-z0-9-_]+)\./i);
if (matched && matched.length > 1) {
const locale = matched[1];
messages[locale] = locales(key);
}
});
return messages;
}
export default createI18n({
legacy: false,
locale: localStorage.locale ?? 'nl',
globalInjection: true,
messages: loadLocaleMessages(),
});
For Vue 3 guys out there struggling with usage of i18n in the Vuex store, I was able to achieve it like this:
translations/index.js
with basic setup
import { createI18n } from 'vue-i18n'
const i18n = createI18n({
fallbackLocale: 'en',
globalInjection: true,
messages: messages
})
export default i18n
main.js
Import store and i18n and use them in Vue app instance
import i18n from './translations'
import store from './store'
const app = createApp(App)
app.use(store)
app.use(i18n)
app.mount('#app')
Vuex store module file with getter example:
import i18n from './translations'
const getters = {
getNotification: (state) => {
...
notification.title = i18n.global.t('notification.title')
...
}
}
I used vue-i18n in Vuex. Maybe it helps to you.
Create vue-i18n.js file like this;
import Vue from "vue";
import VueI18n from "vue-i18n";
// Localisation language list
import { locale as en } from "#/core/config/i18n/en.js";
import { locale as ch } from "#/core/config/i18n/ch.js";
Vue.use(VueI18n);
let messages = {};
messages = { ...messages, en, ch };
// get current selected language
const lang = localStorage.getItem("language") || "en";
// Create VueI18n instance with options
const i18n = new VueI18n({
locale: lang, // set locale
messages // set locale messages
});
export default i18n;
and import it to Vue in main.js file;
import i18n from "#/core/plugins/vue-i18n";
new Vue({
router,
store,
i18n,
render: h => h(App),
}).$mount('#app')
import it inside your store or modules ( i imported in my vuex module);
import i18n from "#/core/plugins/vue-i18n";
then use it wherever you want (action, mutation, setter or getter);
const sample = i18n.t('ERRORS.NETWORKERROR');
en.js file;
export const locale = {
LOGIN: {
OPERATORID: "Operator ID",
SIGNIN:"Sign In",
SCANCARD: "Scan Card"
},
ERRORS: {
NETWORKERROR: "Network error occurred!",
UNAUTHUSERERROR: "Unauthorized user!",
}
};
first, i'm sorry that my English is not good.
...
I want to make vue.js components module.
I tried simple button component module and It works(it include vuex).
I saw this page.
and I want to make some module with 5 components that use both store and vue-router.
so I tried like this.
import LoadingSpinner from './components/common/LodingSpinner.vue';
import Modal from './components/common/Modal.vue';
import InputPage from './components/InputPage.vue';
import Page from './components/Page.vue';
import ProcessingPage from './components/ProcessingPage.vue';
import store from './store/index.js';
import route from './routes/index.js';
export default {
install(Vue, options) {
if (!options || !options.store) {
throw new Error('Please initialise plugin with a Vuex store.')
}
options.store.registerModule('dummylib', store);
options.route.registerModule('dummylib', route);
Vue.component('loading-spinner', LoadingSpinner);
Vue.component('modal', Modal);
Vue.component('input-page', InputPage);
Vue.component('page', Page);
Vue.component('processing-page', ProcessingPage);
}
when i finished it and install in new project, I can't see even App.vue and all components are missing.
Here is the main.js of the new project that will include the module.
import Vue from 'vue';
import App from './App.vue';
import store from './store';
import DummyButton from 'dummylib';
import router from './routes';
import InputPage from 'dummylib';
import Page from 'dummylib';
import ProcessingPage from 'dummylib';
import Modal from 'dummylib';
import LoadingSpinner from 'dummylib';
Vue.config.productionTip = false
Vue.use(DummyButton, {store});
Vue.use(InputPage, { store });
Vue.use(Page, { store });
Vue.use(ProcessingPage, { store });
Vue.use(Modal, { store });
Vue.use(LoadingSpinner);
new Vue({
store,
router,
render: h => h(App),
}).$mount('#app')
how can i solve this problems...
thank you for watching my question with not good english.
i hope you understand my intension.
I created a new project using:
vue create hello-world
Generating a new project that includes the HelloWorld.vue, app.vue, main.js (etc ...) files.
Now I install Axios by following the docs Npm vue-axios:
npm install --save axios vue-axios
I import Axios in the main.js file:
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
And now I run into a problem that I don't understand. The VueAxios docs say you simply use it like so:
const app = Vue.createApp(...)
app.use(VueAxios, axios)
But the way app is created in Vue 3 is different. I think this is where the problem comes from:
createApp(App).mount('#app')
So, how do I correctly import axios?
createApp(App).mount('#app') is effectively the same as:
import Vue from 'vue'
const app = Vue.createApp(App)
app.mount('#app')
// or
import { createApp } from 'vue'
const app = createApp(App)
app.mount('#app')
So following Vue Axios's docs, just insert the line for app.use():
import { createApp } from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
const app = createApp(App)
app.use(VueAxios, axios) // 👈
app.mount('#app')
You could also chain it like this:
createApp(App).use(VueAxios, axios).mount('#app')
demo
You could import only axios and define it as a global property :
Using a bundler (vue cli, vite or webpack ...):
import { createApp } from 'vue'
import axios from 'axios'
const app = createApp(...)
app.config.globalProperties.axios=axios
then use it in any child component like:
Option api :
this.axios.get(...)
in Composition api I recommend to import it directly like :
import axios from 'axios'
const MyComponent = {
setup() {
//use axios here
....
}
}
or you use useAxios from the vueuse (vue composition utilities) :
import { useAxios } from '#vueuse/integrations/useAxios'
...
setup() {
const { data, isFinished } = useAxios('/api/posts')
}
This worked for me at VueJS 3.
npm i vue-axios
import { createApp } from "vue";
import axios from 'axios'
import VueAxios from 'vue-axios'
const app = createApp(App);
app.use(VueAxios)
app.use(axios)
app.mount("#app");
this.axios.get(api).then((response) => {
console.log(response.data)
})
Doc link:
https://www.npmjs.com/package/vue-axios
Overview
React application in which internationalization is required, using i18next to achieve this.
Problem
In project structure there is constants.js (Plain JS) where I am trying to get i18next.t() for translation. Please find the relevant code.
index.js
import React,{Suspense} from "react";
import ReactDOM from "react-dom";
import "./style/index.scss";
import App from "./app";
import createSagaMiddleware from "redux-saga";
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import rootReducer from "./reducers";
import rootSaga from "./sagas";
import './i18n';
const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga);
ReactDOM.render(<Provider store={store}>
<App store={store} />
</Provider>,
document.getElementById("root")
);
App.js
import React from "react";
import "./App.scss";
import MyOrders from "../component/my-orders";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import i18n from 'i18next'
toast.configure({ autoClose: 5000 });
const changeLanguage = (lng) => {
i18n.changeLanguage(lng);
};
const App = () => {
return (
<div className="App">
<div align="left">
<button className="btn btn-group-sm" onClick={() => changeLanguage('de')}>German</button>
<button className="btn btn-group-sm" onClick={() => changeLanguage('en')}>English</button>
</div>
<MyOrders />
</div>
);
};
export default App;
i18n.js
import i18n from "i18next";
import detector from "i18next-browser-languagedetector";
import { reactI18nextModule } from "react-i18next";
import translationEN from '../public/locales/en/translation.json';
import translationDE from '../public/locales/de/translation.json';
// the translations
const resources = {
en: {
translation: translationEN
},
de: {
translation: translationDE
}
};
i18n
.use(detector)
.use(reactI18nextModule) // passes i18n down to react-i18next
.init({
resources,
lng: "en",
fallbackLng: "en", // use en if detected lng is not available
interpolation: {
escapeValue: false // react already safes from xss
}
});
export default i18n;
Question Updates with progress so far
constants.js (Plain JavaScript file, exporting multiple constant objects)
import i18n from "../../i18n";
import { withNamespaces } from "react-i18next";
function parentFunction(){
let constantsMap = new Map();
constantsMap.set("constant1", valueOfConstant1);
....
}
export default withNamespaces()(parentFunction)
translation.js (de)
{
"MODAL": {
"CANCEL": "Stornieren",
"UPDATE": "Aktualisieren",
"SAVE": "Speichern",
"CANCEL_BOD": "Ja, Abbrechen BOD",
"KEEP_BOD": "Nein, behalte BOD",
"NEXT": "Nächster"
}, .....
I tried the following solution with no luck:
Solution
You can import i18n instance from your i18n.js file, it contains t on it.
import i18n from '../i18n';
i18n.t // <- use it.
I used it this way on redux saga
import i18n from "i18next";
toast.error(i18n.t('thereWasAnErrorUpdating'), {
position: toast.POSITION.TOP_CENTER,
autoClose: NOTIFICATION_TIME,
toastId: 'settingInformationFailure'
});