vue强制刷新组件的3种方法

发布于:2024-04-09 ⋅ 阅读:(81) ⋅ 点赞:(0)

通过组件的key值来刷新

(当某个组件的key变化后,组件都会被重新渲染一遍)

<template>
	<el-table
	        :data="data"
	        :key="refresh"
	      >
	      ...
	</el-table>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
	
@Component({})
export default class extends Vue {
	refresh= true
	
	@Watch('data')
	watchData() {
	  this.refresh= !this.refresh
	}
}
</script>

还有通过if来刷新

(当v-if的值发生变化时,组件都会被重新渲染一遍)

<template>
	<el-table
	        v-if="refresh"
	        :data="data"
	      >
	      ...
	</el-table>
</template>
<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
	
@Component({})
export default class extends Vue {
	refresh = true
	
	// 监视data是否发生变化
	@Watch('data')
	watchData() {
		// 移除组件
        this.refresh = false
        // this.$nextTick可实现在DOM 状态更新后,执行传入的方法。
        this.$nextTick(() => {
        	// 重新渲染组件
            this.refresh = true
        })
	}
}
</script>

通过this $forceUpdate强制重新渲染

(如果要在组件内部中进行强制刷新,则可以调用this.$forceUpdate()强制重新渲染组件)

<template>
	<button @click="reflush()">刷新当前组件</button>
</template>
<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
	
@Component({})
export default class extends Vue {
	reflush() {
	    this.$forceUpdate()
	}
}
</script>


网站公告

今日签到

点亮在社区的每一天
去签到