36

I'm learning Vue router. And I want to made programmatic navigation without using <router-link> in templates file. My router and view:

 router = new VueRouter({
        routes: [
            {path : '/videos',  name: 'allVideos', component: Videos },
            {path : '/videos/:id/edit', name: 'editVideo', component: VideoEdit },
        ]
    });

    new Vue({
        el: "#app",
        router,
        created: function(){
            if(!localStorage.hasOwnProperty('auth_token')) {
                window.location.replace('/account/login');
            }

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

So by default I push to 'allVideos' route and inside that component I have a button and method for redirecting to ''editVideo' button:

<button class="btn btn-sm btn-warning" @click="editVideo(video)">Edit</button>

method:

editVideo(video) {router.push({ name: 'editVideo', params: { id: video.id } })},

It works fine. But when I try to get id inside a VideoEdit component using $route.params.id I got error Uncaught ReferenceError: $route is not defined

Maybe it's because I'm not using npm for now just a cdn version of Vue and Vuerouter. Any solutions? Thanks!

Updated: btw in Vue dev tool I see $route instance inside the component

Updated:

var VideoEdit = Vue.component('VideoEdit', {
          template: ` <div class="panel-heading">
                        <h3 class="panel-title">Edit {{vieo.name}}</h3>
                    </div>`,
                data() {
                    return {
                        error: '',
                        video: {},
                }
            },        
            created: function () {
                  console.log($route.params.id);
            },
  })
Aliasgher Nooruddin
  • 493
  • 1
  • 3
  • 15
Bogdan Dubyk
  • 2,860
  • 3
  • 21
  • 39

6 Answers6

52

Thanks to Sandeep Rajoria

we found solution, need to use this.$route except $route inside a component

Community
  • 1
  • 1
Bogdan Dubyk
  • 2,860
  • 3
  • 21
  • 39
10

For those who getting the error after adding this

TypeError: Cannot read property '$route' of undefined

We need to use a regular function instead of ES6 arrow functions

data: function() {
    return {
      usertype: this.$route.params.type
    };
  },

This worked for me.

Kishan Vaghela
  • 7,008
  • 3
  • 36
  • 63
  • I had the same issue inside of `methods`. ``` methods: { forward: ({path}) => $router.push(path) } ``` needed to be ``` methods: { forward: function({ path }) { this.$router.push('register') } } ``` – Seth McClaine Oct 30 '19 at 15:24
7
import Vue from 'vue'
import Router from 'vue-router';

Vue.use(Router)

const router = new VueRouter({
    routes: [
        {path : '/videos',  name: 'allVideos', component: Videos },
        {path : '/videos/:id/edit', name: 'editVideo', component: VideoEdit },
    ]
});

new Vue({
    el: "#app",
    router,
    created: function(){
        if(!localStorage.hasOwnProperty('auth_token')) {
            window.location.replace('/account/login');
        }

        this.$router.push({ name: 'allVideos' });
    }
})
Tran Hoang Hiep
  • 514
  • 5
  • 11
  • 12
    Some narrative would be nice to explain what you did here. – Mad Physicist Apr 25 '17 at 15:28
  • The vuejs router Guide doesn't make it very clear that you need to use Vue.use(VueRouter) if using a module system. https://router.vuejs.org/guide/#javascript – Michael Mar 04 '20 at 22:47
1

If you're using vue v2 & vue-router v2 then in vue-cli generated boilerplate way to access router e.g. from component is to import router (exported in router/index.js)

<script>
  import Router from '../router';

then in your code you can use router functions like:

Router.push('/contacts'); // go to contacts page
Janne
  • 1,441
  • 12
  • 17
1

For those attempting to use es6 arrow functions, another alternative to @Kishan Vaghela is:

methods: {
        gotoRegister() {
            this.$router.push('register')
        }
    }

as explained in the first answer of Methods in ES6 objects: using arrow functions

Seth McClaine
  • 6,298
  • 4
  • 32
  • 53
-1

In my case these previous solutions don't work for me so i did the following

<script> import Router from '../router';

then in your code you can use this one

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