1- main.js
import Vue from 'vue';
import Vuex from 'vuex';
import App from './App';
import { store } from './store'
new Vue({
el: '#app',
store,
render: h => h(App)
})
2- App.vue:在这里我使用按钮来更改语言:
<template>
<div id="app">
<img src="./assets/logo.png" />
<div>
<div>
<h1>{{ "index.title" | translate }}</h1>
<p>{{ $t("index.content", {"type": "nice"}) }}</p>
</div>
<div>
<h1>{{ "home.title" | translate }}</h1>
<p>{{ $t("home.content", {"type": "nice"}) }}</p>
</div>
<div>
<h1>{{ "product.title" | translate }}</h1>
<p>{{ $t("product.content", {"type": "nice"}) }}</p>
<p>{{ $t("product.unit", {"type": "nice"}) }}</p>
</div>
<button @click="setLang('fa')">پارسی</button>
<button @click="setLang('en')">English</button>
<button @click="setLang('ar')">العربیه</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
posts: [],
errors: []
};
},
methods: {
setLang(lang) {
this.$store.dispatch("changeCulture", lang);
}
},
created() {
this.$store.dispatch("changeCulture", "en");
}
};
</script>
3-store > index.js:这里我尝试使用sore、mutation和actions来改变local:
import Vue from 'vue';
import Vuex from 'vuex';
import vuexI18n from 'vuex-i18n';
import translationsEn from '../locals/en.json';
import translationsFa from '../locals/fa.json';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
fallback: 'en',
locale: ''
},
mutations: {
setCulture(state, payload) {
state.locale = payload
Vue.i18n.set(state.locale);
}
},
actions: {
changeCulture({ commit }, payload, adad) {
commit('setCulture', payload)
}
},
getters: {
language(state) {
return state.locale
}
}
})
Vue.use(vuexI18n.plugin, store);
Vue.i18n.add('en', translationsEn);
Vue.i18n.add('fa', translationsFa);
Vue.i18n.set('fa')
4- en.json / fa.json :有些人可能会要求它:
{
"index": {
"title": "Hello",
"content": "This is some {type} content"
},
"home": {
"title": "About us",
"content": "Node developing team"
},
"product": {
"title": "Product",
"content": "Select one product",
"unit": "unit"
}
}
... 4- fa.json 是:
{
"index": {
"title": "سلام",
"content": "به دنیای کد خوش آمدید"
},
"home": {
"title": "درباره ما",
"content": "تیم برنامه نویسی نود"
},
"product": {
"title": "محصولات",
"content": "یک محصول را انتخاب کنید",
"unit": "واحد شمارش"
}
}
它就像一个魅力。