parent.vue
//html
<button @click='alter(1)'>btn1</button>
<button @click='alter(2)'>btn2</button>
<router-view></router-view>
//js
alter(item) {
this.$router.push({name:'classifyEdit',params:{id:item}});
}
child.vue
beforeRouteUpdate(to,from,next){
console.log(to.params.id);
next();
}
为什么只能显示一个按钮的id呢?如何才能点击不同的按钮显示相应的id
已经解决,现在贴一下代码
获取不到参数的原因就是第一次路由渲染之后已经存到了缓存里,第二次就不会触发组件的生命周期钩子,因此获取不到第二个参数,解决方法主要有监听路由参数,使用路由导航守卫beforeRouteUpdate
,我用的后者,以下是代码:
parent.vue
<button @click='alter(1)'>btn1</button>
<button @click='alter(2)'>btn2</button>
<Modal
v-model="moralFlag"
:title="moralTitle">
<router-view></router-view>
<div slot="footer"></div>
</Modal>
alter(item) {
this.$router.push({name:'classifyEdit',query:{id:item.row.id}});
}
child.vue
beforeRouteUpdate(to,from,next){
this.getData(to.query.id);
next();
},
created(){
this.getData(this.$route.query.id);
},
methods: {
getData(id){
console.log(id)
}
两个钩子搭配使用
PS:制作过程中发现beforeRouteUpdate
只能监听query参数无法监听params.
你是在哪里
console.log(this.$route.params.id)
的. 点击两个按钮, 点第一次的时候,router-view
刚创建,created
可以调用, 获取到id
, 点第二次的时候, 就应该是beforeRouteUpdate
的钩子函数了.你再加一个
<router-view></router-iview>
多了一个i
, 请注意