我在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
中获得任何价值,当我第二次点击时,我正在获得价值。
为什么会这样?我想第一次获得价值。
您的问题是由您正在观看更改的事实引起的。为了更好地理解这个问题,这是一个时间表:
$route
MainBody
为Word
,更新传递的道具并调用created
和mounted
从word
的角度来看,没有任何变化,它并没有称之为手表
从任何方法手动解析$route
并不是最干净的解决方案,更好的方法是将道具与观察者结合使用来获取你的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,
},
我建议你在mount()和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()
}