內容目錄
Vuejs 資料異動後如何刷新當前頁面
情境
頁面的表格資料異動後,常常有刪除一筆資料或者新增資料之後需要重新刷新當前頁面的需求。
遇到的問題
- 用vue-router重新路由到當前頁面,頁面不進行刷新
- 採用window.reload(),或者router.go(0)刷新時,整個流覽器進行了重新載入,閃爍。
解決方法
provide / inject 組合
作用:允許一個祖先元件向其所有子孫後代注入一個依賴,不論元件層次有多深,並在起上下游關係成立的時間裡始終生效。
在 App.vue
聲明 reload 方法
控制 router-view 的顯示或隱藏,然後從控制頁面呼叫此 reload ,讓 router-view 重新載入
<template> <div id="app"> <Toast /> <div class="layout-main"> <router-view v-if="isRouterAlive"/> </div> </div> </template> <script> export default { provide(){ return { reload: this.reload } }, data() { return { isRouterAlive: true, }, methods: { reload () { console.log('reload occure') this.isRouterAlive = false; this.$nextTick( ()=> { this.isRouterAlive=true } ) ; }, }, }; </script>
使用 inject 注入呼叫 reload
在操作的頁面 usersManagement.vue
,先將 reload 透過 inject 注入,便可以直接調用 this.reload()
<script> import sysService from '../../services/sysService' export default { inject:['reload'], data(){ return { users: null, userFormData: { username:'', email: '', }, }; }, sysService: null, created() { this.sysService = new sysService(); }, methods:{ submitForm(formName) { this.$refs[formName].validate(async (valid) => { if (valid) { await this.sysService.saveUser(this.userFormData); this.reload(); this.$toast.add({severity:'success', summary: 'Successful', detail: 'User Updated', life: 3000}); this.userDialog = false; } else { this.$toast.add({severity:'error', summary: 'Failure', detail: 'Submit Error', life: 3000}); return false; } }); }, } } </script>
provide / inject 用法
- provide:選項應該是一個物件或返回一個物件的函數。該物件包含可注入其子孫的屬性。
- inject:一個字串陣列,或一個物件,物件的 key 是本地的綁定名
提示:
- provide 和 inject 綁定並不是可回應的。這是刻意為之的。如果你傳入了一個可監聽的物件,那麼其物件的屬性還是可響應的。
- 不能在生命周朝中調用,否則會一直在重新調用(頁面重覆刷新),只能在添加或刪除這樣的操作中,可以使用 this.reload()
註: 若 dataTable 有設定每頁幾筆資料,而當用戶有變更時,它可能會被重置成預設值,這時不妨用 this.$set
& push
的方法來代替。
submitForm(formName) { this.$refs[formName].validate(async (valid) => { if (valid) { let result = await this.sysService.saveUser(this.userFormData); if (this.userFormData.userId) { this.$set(this.users, this.dtFindIndexById(this.users,this.userFormData.userId), result.user); } else { this.userFormData.userId=result.user.userId; this.users.push(this.userFormData); } this.$toast.add({severity:'success', summary: 'Successful', detail: 'User Updated', life: 3000}); this.userDialog = false; } else { this.$toast.add({severity:'error', summary: 'Failure', detail: 'Submit Error', life: 3000}); return false; } }); },
在客製組件 [vuejs] Using v-model on Cust Components 中也可以此方法來顯示正確的資料
你必須 登入 才能發表評論。