應用場景:
在前端頁面進行修改與添加操作時,指向的數據頁面一致。點擊修改按鈕,做數據回顯操作,再去點擊添加按鈕,出現表單頁面,表單頁面顯示還是上次回顯數據,設計的期望效果是清空表單。
定位代碼片段:
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/ 歡迎轉載,一起技術交流探討!