Home

传传的工作甜点

A strong man will struggle with the storms of fade.

Blog About Email Github

2018-12-29
VUE友好刷新页面

场景

在处理列表时,常常有删除一条数据或者新增数据之后需要重新刷新当前页面的需求。

遇到的问题

  • 用vue-router重新路由到当前页面,页面是不进行刷新的
  • 采用window.reload(),或者router.go(0)刷新时,整个浏览器进行了重新加载,闪烁,体验不好

解决方法

provide / inject 组合

作用:允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在起上下游关系成立的时间里始终生效。

我的项目配置

App.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<template>
<div id="app">
<!-- 1.添加 v-if -->
<router-view v-if="isRouterAlive" />
</div>
</template>

<script>
export default {
name: 'App',
provide () { // 2.注册一个方法 reload
return {
reload: this.reload
}
},
data () {
return {
isRouterAlive: true
}
},
methods: {
reload () { // 3. realod 方法实现
this.isRouterAlive = false
this.$nextTick(function () {
this.isRouterAlive = true
console.log('reload')
})
}
}
}
</script>

<style>
</style>

子组件 child.vue

1
2
3
4
5
6
7
inject: ['reload'], // 1.引入方法

methods: { // 2.实现刷新
refreshList () {
this.reload()
}
}

LucienWu

scribble

Blog About Email Github