应用场景:
在前端页面进行修改与添加操作时,指向的数据页面一致。点击修改按钮,做数据回显操作,再去点击添加按钮,出现表单页面,表单页面显示还是上次回显数据,设计的期望效果是清空表单。
定位代码片段:
created () {
this.init()
},
methods: {
init() {
//判断路由是否有id值
if(this.$route.params && this.$route.params.id) {
//获取路由id值
const teacherId = this.$route.params.id
//根据id调用接口查询
this.getTeacherById(teacherId)
} else {//没有id,清空
// alert('teacher...')
//表单清空
this.teacher = {}
}
},
created
方法进行条件判断,通过参数与参数id
判断是否添加。如果添加表单清空,测试发现代码alert('teacher...')
没有执行,所以表单没有实现清空…
问题分析与解决:
路由切换时,如果多次路由切换进入同一个页面,这个页面中的created方法只会执行一次,如同静态代码块!解决方案:使用了watch
来监听路由的变化即可!
watch: {//监听到路由变化
$route(to, from) {
// console.log('watch $route')
this.init()
}
},
created () {
this.init()
},
methods: {
init() {
//判断路由是否有id值
if(this.$route.params && this.$route.params.id) {
//获取路由id值
const teacherId = this.$route.params.id
//根据id调用接口查询
this.getTeacherById(teacherId)
} else {//没有id,清空
// alert('teacher...')
//表单清空
this.teacher = {}
}
},
.........
♚学习、实战、总结、分享,让生活变得更美好!
☞林大侠博客:https://coding0110lin.blog.csdn.net/ 欢迎转载,一起技术交流探讨!