Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue2: How to redirect to another page using routes

How can I redirect to another vue page from my script code. I am using router.push() but cannot redirect to my desired vue page.

Following is my source code.

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>

After running this code I am getting error which states:

ReferenceError: router is not defined at 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/>'
})

Furthermore, I can access that same link from browser http://localhost:8080/#/homepage. But cannot redirect to it from my script code.

like image 316
Zain SMJ Avatar asked Jan 21 '26 14:01

Zain SMJ


1 Answers

import Vue and VueRouter and then call

    Vue.use(VueRouter)

then in your method,

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

EDIT

You need to import both Vue and Vue Router if you want to use it in your code, that's why you are getting router is not defined at eval. And also use

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

Try this in your 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>
like image 73
Justin Lim Avatar answered Jan 23 '26 03:01

Justin Lim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!