一、 vue中使用forceUpdate

作用:在Vue官方文档中指出,$forceUpdate具有强制刷新的作用,迫使vue实例重新(rander)渲染虚拟dom,注意它仅仅影响实例本身和插入插槽内容的子组件,而不是所有子组件。

在vue2中使用

this.$forceUpdate()

vue3中使用

import { getCurrentInstance } from 'vue' // 先引入
setup(){
// 解构赋值 设置别名that,也可不写:that,直接ctx
  	let { ctx: that } = getCurrentInstance()
	that.$forceUpdate()
}

这样使用的时候会报错 Property ‘ctx’ does not exist on type ‘ComponentInternalInstance | null’.

万恶的类型检测

const { ctx: that } = getCurrentInstance() as any

二、vue中使用$nextTick

作用:vue中的nextTick()是在下次 DOM 更新循环结束之后执行延迟回调,在修改数据之后使用$nextTick(),则可以在回调中获取更新后的 DOM。

在vue2中使用

this.visible = false
// 直接使用
this.$nextTick(() => {
   // 要执行的方法
	this.visible = true
})

在vue3中使用

import { nextTick } from 'vue' // 先引入
setup () {
	const visible = ref<boolean>(false)
	// 使用
	nextTick(()=>{
		visible.value = true
	})
	return {
		visible
	}
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐