一旦遇到问题,我就对路由路径有了一个很好的想法,这听起来不再那么聪明了:)。希望你们能看到/找到解决方案。
这是我的route.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();
},
问题出在下面。当用户执行更改语言功能时,我成功更改了lang参数,但是this.$route.name
在旧语言中保持不变。有没有办法“重新加载” 路线,所以会有新的路线路径,其中包括正确的语言?
如果您需要任何其他信息,请告诉我,我会提供。谢谢!
答案 0 :(得分:2)
检查此基本示例,您可以看到根据所选语言而变化的路径。 可以使用诸如vue-i18n之类的翻译插件对此进行改进,也可以将其包装到mixin中以提高可重用性。
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>