業務場景:在管理后台,在執行完,增,刪,改,操作的時候。我們需要刷新一下頁面,重載數據。在JQ中我們會用到location.reload()方法,刷新頁面;在vue中,這里需要用到一個 provide / inject 這對用例。(其他方法:this.$router.go(0),會強制刷新,出現空白頁面體驗不好)
這對選項需要一起使用,以允許一個祖先組件向其所有子孫后代注入一個依賴,不論組件層次有多深,並在起上下游關系成立的時間里始終生效。
實現原理就是通過控制router-view 的顯示與隱藏,來重渲染路由區域,重而達到頁面刷新的效果,show -> flase -> show
具體代碼如下:
1.首先在我們的根組件APP.vue里面,寫入刷新方法,路由初始狀態是顯示的
<template> <div id="app"> <keep-alive> <router-view v-show="$route.meta.keepAlive"/> </keep-alive>
<router-view v-if="isRouterAlive"/> <Tabbar v-show="$route.meta.showFooter"></Tabbar> </div> </template> <script> // 樣式重置 common.css import "./assets/common.css" import SHeader from './components_c/SearchHeader.vue' import Tabbar from './components_c/Tabbar' export default { name: 'App', provide(){ return{ reload:this.reload } }, data(){ return{ isRouterAlive:true } }, components:{ SHeader, Tabbar }, methods: { reload (){ this.isRouterAlive = false this.$nextTick(function(){ this.isRouterAlive = true }) } } } </script> <style lang="scss" scoped> </style>
<router-view v-if="isRouterAlive"></router-view> 在isRouterAlive 為true的地方 使用刷新 ,然后在其他組件或者頁面中調用相應方法就行
2、然后在子組件中引用
3、執行完相應操作之后,調用reload方法