0%

Vue组件刷新

在特定情况下,如果需要执行刷新操作,有四种可选方案:

  1. 借助router.go(0)方法,刷新整个页面
  2. 使用forceUpdate()方法,刷新当前组件
  3. 使用v-if标记,刷新子组件
  4. 使用:key属性,通过改变key的值来达到刷新子组件的目的

forceUpdate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template>
<div id="app">
<button @click="refresh">Refresh</button>
</div>
</template>

<script lang="ts">
export default {
methods: {
refresh () {
this.$forceUpdate(); // 刷新当前组件
// this.$router.go(0); // 刷新整个页面
}
}
};
</script>

v-if

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
<div id="app">
<button @click="refresh">Refresh</button>
<SubComponent v-if="flag">This is SubComponent!</SubComponent>
</div>
</template>

<script lang="ts">
export default {
data: () => ({
flag: true
}),
methods: {
refresh () {
this.flag = false;
this.$nextTick(() => {
this.flag = true;
});
}
}
};
</script>

:key

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template>
<div id="app">
<button @click="refresh">Refresh</button>
<SubComponent :key="key">This is SubComponent!</SubComponent>
</div>
</template>

<script lang="ts">
export default {
data: () => ({
key: Math.random()
}),
methods: {
refresh () {
this.key = Math.random();
}
}
};
</script>