我在vue组件文件中有一个链接,如下所示。
<li v-for="(word,index) in allWord" v-bind:key="index">
<router-link :to="{ name: 'word', params: {id: word.id } }">
{{word}}
</router-link>
</li>
我在index.js
文件中的路由设置如下
export default new Router({
mode: 'history',
routes: [
{
path: '/',
component: MainBody
},
{ path: '/word/:id',
name: 'word',
component: Word
}
]
});
我得到的URL如下
http://localhost:8080/word/4
我正在尝试捕获word.vue
中的URL参数,如下所示
<script>
export default {
watch: {
'$route': 'routeChanged'
},
methods: {
routeChanged () {
console.log(this.$route.params.id);
}
}
}
</script>
问题是,当我点击<li></li>
时,我在console
中没有得到任何值,当我第二次点击时,我得到了值。
为什么会发生这种事?我想第一次得到价值。
您的问题是由您正在观察更改这一事实引起的。为了更好地理解这个问题,这里有一个时间表:
- 用户点击"http://localhost:8080/word/4">
- Vue路由器更新
$route
- 路由器视图更新视图,将
MainBody
换成Word
,更新传递的道具并调用created
和mounted
由于从word
的角度来看,没有任何变化,因此它不会调用手表
从任何方法手动解析$route
都不是最干净的解决方案,最好只是将props与观察者结合使用,以获得您的id:
<script>
export default {
props: {
id: String,
},
created() {
this.routeChanged();
},
watch: {
'id': 'routeChanged',
},
methods: {
routeChanged () {
console.log(this.id);
},
},
};
</script>
如果使用以下选项,请确保在路由器中指定props: true
:
{ path: '/word/:id',
name: 'word',
component: Word,
props: true,
},
我建议您捕获mounted((和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()
}