在VUE 3路由器中更改参数

问题描述 投票:0回答:2

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})
当我执行代码时,路由参数没有更改,也不会在控制台中记录错误。有人在VUE 3中知道解决此问题的解决方案。

提前感谢

这样更改您的路由参数的糟糕方式。 Instead,用相同的
javascript vuejs3 vue-router router vue-i18n
2个回答
4
投票
替换您的路线,相同的

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

0
投票

/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(); });

	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.