我想在Vue.js中做一个类似于香草javascript的重定向

window.location.href = 'some_url'

我如何在Vue.js中实现这一点?


当前回答

如果你想路由到另一个页面,使用这个

this.$router.push({path: '/pagename'});

如果你想路由到另一个页面的参数使用这个

this.$router.push({
  path: '/pagename', 
  params: {
    param1: 'value1', 
    param2: 'value2'
  }
});

其他回答

Vue3.js重定向

ve3 js全局重定向可以在main.ts中使用此方法定义

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>

如果有人想从一个页面/a永久重定向到另一个页面/b


我们可以使用在router.js中添加的redirect:选项。例如,当用户输入根或基url /时,我们想要将用户重定向到一个单独的页面:

const router = new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/",
      redirect: "/someOtherPage",
      name: "home",
      component: Home,
      // () =>
      // import(/* webpackChunkName: "home" */ "./views/pageView/home.vue"),

    },
   ]

你也可以直接在模板上使用v-bind,就像…

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

:是v-bind的缩写。

在组件脚本标记中,您可以使用路由器并执行类似的操作

this.$router.push('/url-path')

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

router.replace(数据。电流+ '?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)
});

);