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

新手上路,请多包涵

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

以下是我的源代码。

源代码/路由器/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
    }
  ]
})

源代码/组件/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 中定义

源代码/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 访问同一个链接。但无法从我的脚本代码重定向到它。

原文由 Zain SMJ 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 985
2 个回答

感谢反馈的朋友。我没有在我的 vue 上导入我的路由器文件。更新后的代码行是:

源代码/组件/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>

原文由 Zain SMJ 发布,翻译遵循 CC BY-SA 4.0 许可协议

导入 Vue 和 VueRouter 然后调用

    Vue.use(VueRouter)

然后在你的方法中,

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

编辑

如果你想在你的代码中使用它,你需要同时导入 Vue 和 Vue Router,这就是为什么你得到 router is not defined at 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>

原文由 Justin Lim 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题