Vue router issue

懵懂的女人 提交于 2019-12-11 17:07:39

问题


I have a link like below in a vue component file.

<li v-for="(word,index) in allWord" v-bind:key="index">
    <router-link :to="{ name: 'word', params: {id: word.id } }">
       {{word}}
    </router-link> 
</li>

My route settings in index.js file is like below

export default new Router({
    mode: 'history',
    routes: [
        {   
            path: '/',          
            component: MainBody 
        },
        {   path: '/word/:id',
            name: 'word',   
            component: Word 
        }
    ]
});

I am getting URL like below

http://localhost:8080/word/4

I am trying to catch URL parameter in word.vue is like below

<script>
    export default {
        watch: {
            '$route': 'routeChanged'
        },
        methods: {
            routeChanged () {
                console.log(this.$route.params.id);
            }
        }
    }
</script>

The issue is when I click on the <li></li> I am not getting any value in console, I am getting value when I click second time.

Why it is happening ? I would like to get value first time.


回答1:


Your issue is caused by that fact that you are watching changes. To better understand this issue, here is a timeline:

  1. User clicks "http://localhost:8080/word/4"
  2. Vue router updates $route
  3. Router view updates the view, swapping out MainBody for Word, updates the props passed and calls created and mounted

Since from the view of word, nothing has changed, it doesn't calls the watch

Manually parsing $route from any method isn't the cleanest solution, better is just to use the props in combination with the watcher to get your id:

<script>
    export default {
        props: {
             id: String,
        },
        created() {
             this.routeChanged();
        },
        watch: {
            'id': 'routeChanged',
        },
        methods: {
            routeChanged () {
                console.log(this.id);
            },
        },
    };
</script>

Make sure to specify props: true in your router if using this:

    {   path: '/word/:id',
        name: 'word',   
        component: Word,
        props: true,
    },



回答2:


I suggest you to catch the value in the mounted() and updated().

methods: {
  getid: function()
  {
     this.wordid = this.$route.params.id
  } 
},

watch: {
  wordid: function(val) {
    console.log(this.wordid) // or console.log(val)
  }
},
mounted()
{
   this.getid()
},
updated()
{
 this.getid()
}


来源:https://stackoverflow.com/questions/51244073/vue-router-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!