问题:当使用路由参数时,例如从
/content?id=1到content?id=2,此时原来的组件实例会被复用。这也意味着组件的生命周期钩子不会再被调用,此时vue应该如何响应路由参数的变化?
参考答案:
复用组件时,想对路由参数的变化作出响应的话, 可以watch (监测变化) $route 对象:
const User = { template: '...', watch: { '$route' (to, from) { // 对路由变化作出响应... } } }
或者使用 2.2 中引入的 beforeRouteUpdate 守卫:
const User = { template: '...', beforeRouteUpdate (to, from, next) { // react to route changes... // don't forget to call next() } }
beforeRouteUpdate适用场景
在进入一个路由页面的时候,再次点击进入这个路由页面并且多传递一个参数的时候,created里 不会触发,思考了几分钟,想到是路由没有变化只是更新了参数,就想到了beforeRouteUpdate
beforeRouteUpdate是路由更新时触发的钩子函数
有三个参数 to,from ,next
beforeRouteUpdate(to,from,next){ let a = to.query.a next() }
to表示去哪里,跳转到那个页面
from 表示 来自那个页面
next() 表示继续执行页面,要加上的
