问题代码❌
created() { this.init() }, methods: { init(){ if(this.$route.params && this.$route.params.id){ //从路径获取id值 const id = this.$route.params.id //调用根据id查询的方法 this.getInfo(id) }else { //如果没有值则清空表单 this.teacher= {} } } }原因是created()在页面渲染之前执行一次,执行一次后不再加载了。
解决办法⚡️加上路由监听使每次跳转后都会触发init()方法进行判断清空表单
created() { this.init() }, watch: { //监听 $route(to, from) { //路由变化方式,路由发生变化,方法就会执行 this.init() } }, methods: { init(){ if(this.$route.params && this.$route.params.id){ //从路径获取id值 const id = this.$route.params.id //调用根据id查询的方法 this.getInfo(id) }else { //如果没有值则清空表单 this.teacher= {} } } }