Vue組件刷新解決方案:
- 刷新整個(gè)頁(yè)面
- 使用v-if標(biāo)記
- forceUpdate
- key-changing
1.刷新整個(gè)頁(yè)面:體驗(yàn)感不好,一般不建議使用
//其中兩個(gè)刷新整個(gè)頁(yè)面的方法
window.location.reload();
this.$router.go(0)
2.使用v-if標(biāo)記(條件渲染)
<template>
<div>
<span v-if="isShow"></span>
</div>
</template>
<script>
export default {
data() {
return {
isShow: false
}
},
methods: {
setData() {
this.isShow = !this.isShow
}
}
}
</script>
3.使用內(nèi)置的forceUpdate方法:組件內(nèi)置$forceUpdate方法,使用前需要在配置中啟用。
import Vue from 'vue'
Vue.forceUpdate()
export default {
methods: {
setData() {
this.$forceUpdate()
}
}
}
4.使用key-changing優(yōu)化組件: vue使用key標(biāo)記組件身份,當(dāng)key改變時(shí)就是釋放原始組件求摇,重新加載新的組件。
<template>
<div>
<span :key="key"></span>
</div>
</template>
<script>
export default {
data() {
return {
key: 0
}
},
methods: {
setData() {
this.key += 1
}
}
}
</script>
注意:
1.如果要在組件內(nèi)部中進(jìn)行強(qiáng)制刷新
調(diào)用this.$forceUpdate()強(qiáng)制重新渲染組件
2.如果是刷新某個(gè)子組件
使用v-if指令的特性
使用key-changing,當(dāng)組件的key 值變更時(shí),會(huì)自動(dòng)的重新渲染