问题
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:
- User clicks "http://localhost:8080/word/4"
- Vue router updates
$route
- Router view updates the view, swapping out
MainBody
forWord
, updates the props passed and callscreated
andmounted
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