首页 文章

Vue2:如何使用路由重定向到另一个页面

提问于
浏览
1

如何从我的脚本代码重定向到另一个vue页面 . 我正在使用router.push()但无法重定向到我想要的vue页面 .

以下是我的源代码 .

src/router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import HomePage from '@/components/HomePage'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'IndexPage',
      component: IndexPage
    },
    {
      path: '/homepage',
      name: 'HomePage',
      component: HomePage
    }
  ]
})

src/components/IndexPage.vue

<script>
  import VueRouter from 'vue-router'

  export default {
    name: 'IndexPage',
    methods: {
      redirectUser() { // this method is called on button click
         if (1 == 1)
         {
            router.push('/homepage');
            //this.$router.push('/homepage');
         }
      }
    }
  }
</script>

运行此代码后,我收到错误,指出:

ReferenceError:未在eval中定义路由器

src/main.js

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

window.Vue = Vue

new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

此外,我可以从浏览器http://localhost:8080/#/homepage访问相同的链接 . 但无法从我的脚本代码重定向到它 .

4 回答

  • 1

    您可以尝试以下代码:

    function redirect(page) {
      window.location.href = page;
    }
    
  • 1

    使用组件实例属性访问路由器:

    this.$router.push({name: 'HomePage'})
    

    你有你的应用程序吗?

    new Vue({
      router,
      render: h => h(App)
    }).$mount('#app')
    
  • 1

    导入Vue和VueRouter,然后调用

    Vue.use(VueRouter)
    

    那么在你的方法中,

    this.$router.push({name: 'HomePage'})
    

    编辑

    如果要在代码中使用它,则需要导入Vue和Vue路由器,这就是为什么在eval中没有定义路由器的原因 . 并且还使用

    this.$router.push('/homepage');
    

    试试 src/components/IndexPage.vue

    <script>
      import Vue from 'vue'
      import VueRouter from 'vue-router'
    
      Vue.use(VueRouter)
    
      export default {
        name: 'IndexPage',
        methods: {
          redirectUser() { // this method is called on button click
            if (1 == 1)
            {
               this.$router.push('/homepage');
            }
          }
        }
      }
    </script>
    
  • -2

    Thanx为反馈朋友 . 我没有在我的vue上导入我的路由器文件 . 更新的代码行是:

    src/components/IndexPage.vue

    <script>
      import router from '../router/index.js'  // Just added this line and code works !!
    
      export default {
        name: 'IndexPage',
        methods: {
          redirectUser() { // this method is called on button click
             if (1 == 1)
             {
                router.push({name: 'HomePage'})
             }
          }
        }
      }
    </script>
    

相关问题