vue vue3中使用nextTick和forceUpdate及注意事项

一、 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
	}
}
Vue 3使用`nextTick`与 Vue 2 使用`nextTick`存在以下区别: - **实现位置**:Vue 3 的`nextTick`实现主要在`packages/runtime-core/src/scheduler.ts`文件中,而 Vue 2 未提及特定的实现文件位置 [^3]。 - **异步执行方式选择**:Vue 2 采用了降级策略来选择最佳的异步执行方式,优先级为首选`Promise`(微任务),次选`MutationObserver`(微任务),再次选`setImmediate`(宏任务),最后选择`setTimeout`(宏任务);Vue 3 基本实现使用`Promise.resolve()`,将`nextTick`的操作放入微任务队列中 [^5]。 - **执行顺序时机**:Vue 2 每次调用`nextTick(cb)`,将`cb`放入`callbacks`队列中,只要`pending === false`,就启动微任务(`Promise.then`),微任务执行`flushCallbacks`,依次调用`callbacks`队列中的所有回调;Vue 3 即使`nextTick`赋值操作之前执行也不会影响到赋值操作加入的回调的执行顺序,并且在执行了赋值操作之后,再执行`nextTick`,会等到组件实际的更新操作完成之后,才会将`nextTick`加入微任务队列中准备执行 [^1][^2]。 ### 代码示例 #### Vue 2 ```vue <template> <div> <button @click="updateData">更新数据</button> <p>{{ message }}</p> </div> </template> <script> export default { data() { return { message: &#39;原始数据&#39; }; }, methods: { updateData() { this.message = &#39;更新后的数据&#39;; this.$nextTick(() => { console.log(&#39;DOM 已更新&#39;); }); } } }; </script> ``` #### Vue 3 ```vue <template> <div> <button @click="updateData">更新数据</button> <p>{{ message }}</p> </div> </template> <script setup> import { ref, nextTick } from &#39;vue&#39;; const message = ref(&#39;原始数据&#39;); const updateData = async () => { message.value = &#39;更新后的数据&#39;; await nextTick(); console.log(&#39;DOM 已更新&#39;); }; </script> ```
评论 3
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值