Vue $route is not defined

后端 未结 6 1202
面向向阳花
面向向阳花 2021-01-01 09:05

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

 ro         


        
相关标签:
6条回答
  • 2021-01-01 09:39

    Thanks to Sandeep Rajoria

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

    0 讨论(0)
  • 2021-01-01 09:51

    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
    
    0 讨论(0)
  • 2021-01-01 09:51

    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

    0 讨论(0)
  • 2021-01-01 09:52

    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.

    0 讨论(0)
  • 2021-01-01 09:53

    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');

    0 讨论(0)
  • 2021-01-01 09:55
    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' });
        }
    })
    
    0 讨论(0)
提交回复
热议问题