vue2、vue3中使用$forceUpdate()

简介: vue2、vue3中使用$forceUpdate()

在vue.js中使用this.$forceUpdate()是强制更新方法,作用是触发vue的update方法。可以用在解决数据对象新增属性和数组新增数据,出现页面不渲染的问题。

在前端开发过程中数据处理尤为重要,在使用Vue时我们会事先定义好数据,数据中包含基本数据、对象、数组,其中对象中可能还会有数组,数组中也还会有数组或者对象,这样就形成了深结构数据。我们在给这些深层次的数据赋值或者给对象添加新的属性,页面上的数据并不会同步更新,这是因为受js的限制vue不能检测到对象属性的添加或者删除,所以vue不允许在已经定义好的数据上动态的添加新的属性值。针对此种情况,此时我们可以使用vue的强制刷新方法,在赋值完成之后调用this.$forceUpdate(),这样页面上就能加载我们改变的数据。

在vue2中直接

this.$forceUpdate()

在vue3中直接

import { getCurrentInstance, ComponentInternalInstance } from "vue";
setup(){
//解构赋值 设置别名that  也可不写  :that  直接ctx
//ctx 得到普通对象
//proxy得到响应式对象
// 推荐使用第二种proxy 严谨写法
// 第一种写法
    let {ctx:that, proxy}:any = getCurrentInstance()
  that.$forceUpdate()
// 第二种写法
  const { proxy } = getCurrentInstance() as ComponentInternalInstance
  proxy!.$forceUpdate()
}

参考:

http://t.csdn.cn/57Ghh

目录
相关文章
|
3天前
|
JavaScript 前端开发 CDN
vue3速览
vue3速览
14 0
|
3天前
|
设计模式 JavaScript 前端开发
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
|
3天前
|
JavaScript API
Vue3 官方文档速通(中)
Vue3 官方文档速通(中)
20 0
|
3天前
|
缓存 JavaScript 前端开发
Vue3 官方文档速通(上)
Vue3 官方文档速通(上)
24 0
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
8 1
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
8 0
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
8 0
|
3天前
|
JavaScript 前端开发 API
Vue3 系列:从0开始学习vue3.0
Vue3 系列:从0开始学习vue3.0
9 1
|
3天前
|
网络架构
Vue3 系列:vue-router
Vue3 系列:vue-router
9 2
|
3天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之一:基础项目构建
Vue3+Vite+Pinia+Naive后台管理系统搭建之一:基础项目构建
7 1