在特定情况下,如果需要执行刷新操作,有四种可选方案:
- 借助
router.go(0)
方法,刷新整个页面
- 使用
forceUpdate()
方法,刷新当前组件
- 使用
v-if
标记,刷新子组件
- 使用
: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(); } } }; </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>
|