i试图使用VUE路由器更改路由参数。 我的路线如下:
/document/:id?/:lang?/edit
ID和lang(语言)是参数。 我想使用JavaScript更改参数lang,而无需更改路线的其余部分。我尝试应用以下解决方案(发现Here)。该解决方案是针对VUE 2而不是3的。因此,我尝试制作一个更新的版本。 这是我的代码:
let params = this.$route.params
params.lang = 'en'
this.$router.push({params:params})
提前感谢
这样更改您的路由参数的糟糕方式。 Instead,用相同的
id
lang
:
this.$router.replace({
name: this.$route.name,
params: {
id: this.$route.params.id,
lang: 'en' // or whatever you want
}
})
如果需要时,不要忘记注意路线的更改:
watch: {
$route(to, from) {
// if anything needs to be done when the route changes
}
}
我在VUE 3中使用VUE-I18N V9这样做了这样的事情:
/src/i18n/index.js
/src/components/localeswitcher.vue
import i18n from '@/i18n';
...
watch(() => i18n.global.locale.value, () => {
router.replace({
name: route.name,
params: {
lang: i18n.global.locale.value,
},
});
});
/src/router/index.js
const routes = [
{
path: '/',
redirect: 'lang'
},
{
path: '/:lang',
name: 'lang',
component: HomePage,
},
{
path: '/:lang/content/:contentId',
name: 'guide.content',
component: () => import('@/views/ContentRoot.vue'),
children: [
{
path: '',
name: 'guide.content.root',
component: ContentPage,
},
{
path: 'video',
name: 'guide.content.video',
component: ShowVideo,
},
],
},
{
path: '/:catchAll(.*)',
component: () => import('@/views/404.vue'),
hidden: true,
},
];
router.beforeEach((to, from, next) => {
const locale = to.params.lang; // Retrieve the current locale set in the URL
// Check if the locale the user is trying to access is authorized.
// In a larger application that supports lots of languages, you may want to store
// all the locales in a separate array
if (!['en', 'es'].includes(locale)) {
return next(i18n.global.locale.value);
}
// Changing the language from the URL (either manually or with a link) is possible this way
i18n.global.locale.value = locale;
return next();
});