1、问题是什么?
问题说明: 登录后台主页面,查看讲师列表信息。点击修改讲师信息,数据显示在页面的文本框中,再去点击菜单之后的添加讲师,页面的文本框中依旧显示着刚刚点击修改讲师信息的内容,页面内容未清空。
正常状态:
点击菜单目录中添加讲师选项,跳转添加讲师页面,页面内容应该被清空。
2、如何解决bug?
(1)操作:直接在钩子方法中对应的if语句中添加else语句,执行清空页面数据操作。
created() {
console.log(this.$route.params.id);
if (this.$route.params && this.$route.params.id) {
this.id = this.$route.params.id;
teacher.getTeacherById(this.id).then(response => {
this.eduTeacher = response.data.eduTeacher;
});
}else{
//添加讲师清空数据
console.log('添加讲师清空数据!!!!!')
this.eduTeacher ={}
}
}
(2)结果:出现的Bug未得到解决,数据仍然未被清空。
(3)分析原因:添加的代码未得到执行,从而导致数据未被清空。
3、bug未解决的根本原因
Created()钩子方法,在路由切换页面时只会执行一次。
4、解决Bug最佳方案
(1)使用vue的侦听属性来实现清空数据的方法。
watch: {
$route(to, from) {
console.log("watch $route");
this.init();
}
},
(2)改造方法
created() {
console.log(this.$route.params.id);
this.init()
},
methods: {
//页面初始化
init() {
if (this.$route.params && this.$route.params.id) {
this.id = this.$route.params.id;
teacher.getTeacherById(this.id).then(response => {
this.eduTeacher = response.data.eduTeacher;
});
} else {
//添加讲师清空数据
console.log("添加讲师清空数据!!!!!");
this.eduTeacher = {};
}
},
(3)结果:出现的Bug得到解决,数据被清空。
(4)分析原因:添加的代码得到执行,所以数据被清空,vue侦听属性可用来解决路由切换造成的页面数据回显问题。