在vue的项目中刷新功能你会怎么写?
我以前一直用this.$router.go(0)这个方法用户体验很很差,由于页面会闪动一下刷新
直到我发现了这个方法 provide /inject
不过这个方法貌似有兼容问题,首先要肯定一下你的vue版本,此方法适用vue 2.20+
原理:此方法使用的是v-if来控制router-view的显示或隐藏,v-if从false变为true时,vue会从新渲染router-view区域,因此当参数变化时,只需让v-if 从true => false => true,就能实现页面刷新
首先,找到本身的route-viewvue
//App.vue <template> <div id="app"> <router-view v-if="isRouterAlive"/> </div> </template> <script> export default { name: 'App', provide() { return { reload: this.reload//调用reload方法 } }, data() { return { isRouterAlive: true//一开始router-view为true } }, methods: { reload() { this.isRouterAlive = false //在修改数据以后使用 $nextTick,则能够在回调中获取更新后的 DOM this.$nextTick(() => { this.isRouterAlive = true }) } } } </script>
而后在<route-view>下显示的vue页面中进行以下操做app
export default { name: 'newproduct', inject:['reload'],//在export default下面加上这一段 method:{ //调用App.vue下的this.reload()方法,来改变v-if的状态 clickDiv(){//刷新按钮调用的方法 this.reload() } }
就ok了ide
加油!天天进步一点点!this