我对路径的翻译有了一个很好的想法,听起来不再那么聪明了:),一旦遇到问题。我希望你们能找到解决办法。
这是我的routes.js文件,其中定义了路由
export default [
{
path: '/:lang',
component: {
template: '<router-view></router-view>'
},
children: [
{
path: '',
name: 'Home',
component: load('Home')
},
{
path: translatePath('contact'),
name: 'Contact',
component: load('Contact')
},
{
path: translatePath('cookiePolicy'),
name: 'CookiePolicy',
component: load('CookiePolicy')
},
]
},
]
// and my simple function for translating paths
function translatePath(path) {
let lang = Cookie.get('locale');
let pathTranslations = {
en: {
contact: 'contact',
cookiePolicy: 'cookie-policy',
},
sl: {
contact: 'kontakt',
cookiePolicy: 'piskotki',
}
};
return pathTranslations[lang][path];
}这是我的组件中的变更语言功能。
setLocale(locale) {
let selectedLanguage = locale.toLowerCase();
this.$my.locale.setLocale(selectedLanguage); // update cookie locale
console.log(this.$route.name);
this.$router.replace({ name: this.$route.name, params: { lang: selectedLanguage } });
location.reload();
},问题就在后面。当用户执行更改语言功能时,我成功地更改了language,但是this.$route.name在旧语言中保持不变。是否有一种“重新加载”路由的方法,因此将有新的路由路径,其中将包括适当的语言?
如果您需要更多的信息,请告诉我,我会提供。谢谢!
发布于 2018-12-31 12:42:07
检查这个基本示例,您可以看到根据所选语言更改的路径。可以使用一些翻译插件(如vue-i18n )来改进这一点,也可以将其封装到一个混合器中,以获得更多的可重用性。
const Home = {
template: '<div>Home</div>'
}
const Contact = {
template: '<div>CONTACT ==> {{$route.path}}</div>'
}
const Cookie = {
template: '<div>COOKIE ==> {{$route.path}}</div>'
}
const router = new VueRouter({
routes: [{
name: 'home',
path: '/',
component: Home
},
{
name: 'contact',
path: '/:pathTranslation',
component: Contact
},
{
name: 'cookies',
path: '/:pathTranslation',
component: Cookie
}
]
})
new Vue({
router,
el: '#app',
data: {
lang: 'IT',
translations: {
IT: {
contact: 'Contatti',
cookies: 'Cookies IT',
},
EN: {
contact: 'Contacts',
cookies: 'Cookies EN',
}
}
},
watch: {
lang: function(newLang) {
this.goto(this.$route.name, newLang);
}
},
methods: {
goto(path, lang=null) {
this.$router.replace({
name: path,
params: {
pathTranslation: this.translations[lang || this.lang][path]
}
});
}
}
})<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<select v-model="lang">
<option value="IT">IT</option>
<option value="EN">EN</option>
</select>
<button @click="goto('contact')">To contact</button>
<button @click="goto('cookies')">To cookies</button>
<router-view></router-view>
</div>
https://stackoverflow.com/questions/53962420
复制相似问题