vue-router导航切换 时,如果两个路由都渲染同个组件,组件会重(chong)用,
组件的生命周期钩子(created)不会再被调用, 使得组件的一些数据无法根据 path的改变得到更新
因此:
1、我们可以在watch中监听路由的变化,当路由变化时,重新调用created中的内容
2、在init方法中我们判断路由的变化,如果是修改路由,则从api获取表单数据,
如果是新增路由,则重新初始化表单数据
watch: {
$route(to, from) {
console.log('watch $route')
this.init()
}
},
created() {
console.log('created')
this.init()
},
methods: {
init() {
if (this.$route.params && this.$route.params.id) {
const id = this.$route.params.id
this.fetchDataById(id)
}
},