Vue.js重定向到另一个页面

241

我想在Vue.js中进行类似于原生JavaScript的重定向。

window.location.href = 'some_url'

我该如何在Vue.js中实现这个?


1
你的意思是重定向到Vue路由器中定义的路由'/my/vuerouter/url',还是重定向到http://some-url.com? - hitautodestruct
19个回答

5

我正在使用Vue3,这对我有用

router.push({ name: 'myRoute' })

1
目前这是唯一有效的答案。 - Joseph Astrahan
如果您正在使用组合式 API,请使用 this.$router.push('/path'),否则请返回已翻译的文本。 - Renier

5

您还可以直接将 v-bind 应用到模板中,例如...

<a :href="'/path-to-route/' + IdVariable">

:v-bind 的缩写。


2
你也可以使用ES6语法::href="/path-to-route/${IdVariable}"。 - menepet

5

this.$router.push可以用于在Vue.js中重定向页面。

this.$router.push(url);

例如,这个方法 this.$router.push('home') 不会刷新页面。


2
如果您正在使用Composition API,可以采用以下方式实现:
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()

router.push({ name: 'about' })
</script>

您可以使用Vue devtools来检查您的路由名称。

enter image description here

我建议您使用name,因为如果有一天您想更新某个路径,您将不需要重写所有的按钮/链接。

你还可以通过使用this.$router.push('about')来引用名称自动地将其与Mohammad Mahdi KouchakYazdi的回答结合起来。 - undefined
1
@DirkSchumacher 说实话,这种方法是推动字符串而不是路由名称,与使用名称相比,非常不同且不够灵活,如果有一天需要更新终点,就会变得麻烦。而如果使用名称,你仍然可以从内部保持代码不变。 - undefined

1
保持与您最初的请求一致:

window.location.href = 'some_url'

你可以像这样做:

你可以做类似于这样的事情:

<div @click="this.window.location='some_url'">
</div>

请注意,这并没有利用Vue的路由器功能。但如果你想要"在Vue.js中进行类似于纯JavaScript的重定向",这个方法可以使用。

0

Vue3.js 重定向

在 main.ts 中,可以使用以下方法定义 Vue3 js 全局重定向。

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.config.globalProperties.$redirect = (page) => {router.push(page)}
app.use(router).mount('#app')

组件

<button @click="$redirect('/login')" type="button" class="btn ">Login</button>

0
<div id="app">
   <a :href="path" />Link</a>
</div>

<script>
      new Vue({
        el: '#app',
        data: {
          path: 'https://www.google.com/'
        }
      });
</script> enter code here

0
在使用Laravel + Inertia的情况下: this.$inertia.get(route('route.name', this.modelId));

0

从API获取特定页面 最简单的方法是向URL添加另一个参数,以打破缓存。

router.replace(data.current + '?t=' + (new Date()).getTime())

例如:

router.beforeEach((to, from, next) => {

axios
    .get('http://domazin.com/currentpage')
    .then(response => {
     const data = response.data
       if (to.path != data.current) {
              router.replace(data.current + '?t=' + (new Date()).getTime())
       } else {
          next()
       }
    })
    .catch(error => {
        console.log(error)
});

);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接