前言
Vue的双向绑定属于自动档;在特定的情况下,需要手动触发“刷新”操作,目前有四种方案可以选择:
- 刷新整个页面(最low的,可以借助route机制)
- 使用v-if标记(比较low的)
- 使用内置的forceUpdate方法(较好的)
- 使用key-changing优化组件(最好的)
一、刷新整个页面
router.go(0)
二、使用v-if标记
如果是刷新某个子组件,则可以通过v-if指令实现。我们知道,当v-if的值发生变化时,组件都会被重新渲染一遍。因此,利用v-if指令的特性,可以达到强制刷新组件的目的。
<template>
<comp v-if="refresh"></comp>
<button @click="refreshComp()">刷新comp组件</button>
</template>
<script>
import comp from '@/views/comp.vue'
export default {
name: 'parentComp',
data() {
return {
refresh: true
}
},
methods: {
refreshComp() {
// 移除组件
this.refresh = false
// 在组件移除后,重新渲染组件
// this.$nextTick可实现在DOM 状态更新后,执行传入的方法。
this.$nextTick(() => {
this.refresh = true
})
}
}
}
</script>
三、forceUpdate
组件内置$forceUpdate方法,使用前需要在配置中启用。
import Vue from 'vue'
Vue.forceUpdate()
<template>
<div>
<button @click="handleUpdateClick()">Refresh当前组件</button>
</div>
</template>
export default {
methods: {
handleUpdateClick() {
// built-in
this.$forceUpdate()
}
}
}
四、key-changing
原理很简单,vue使用key标记组件身份,当key改变时就是释放原始组件,重新加载新的组件。
<template>
<div>
<span :key