1

vue3 清空reactive的多种方式

 2 months ago
source link: https://blog.51cto.com/lenglingx/10245533
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

这是引用别人的资料

在 Vue3 中,可以使用 reactive 函数创建响应式对象。这些响应式对象可以跟踪其属性的变化并且自动地更新视图。但是在某些情况下,我们可能需要清空这些响应式对象。下面是一些方法来清空 Vue3 reactive。

方法一:使用 Object.assign

可以使用 Object.assign 将一个空对象分配给可观察对象来清空它。例如:

import { reactive } from 'vue'

const obj = reactive({ name: 'John', age: 25 })

Object.assign(obj, {})

这将清空 obj 对象。但是请注意,这种方法只能清空对象上的属性,不能删除对象本身。

方法二:使用 Object.keys 和 for...in 循环

可以使用 Object.keys 得到对象的属性名称列表,然后使用 for...in 循环将每个属性设置为 undefined 或 null。例如:

import { reactive } from 'vue'

const obj = reactive({ name: 'John', age: 25 })

for (const key in Object.keys(obj)) {
  obj[key] = undefined
}

这将清空 obj 对象。但是请注意,这种方法只能清空对象上的属性,不能删除对象本身。

方法三:使用 delete 操作符

可以使用 delete 操作符删除对象的每个属性。例如:

import { reactive } from 'vue'

const obj = reactive({ name: 'John', age: 25 })

for (const key in obj) {
  delete obj[key]
}

这将清空 obj 对象。但是请注意,这种方法只能清空对象上的属性,不能删除对象本身。

方法四:重新赋值

可以将可观察对象设置为一个新的空对象。例如:

import { reactive } from 'vue'

let obj = reactive({ name: 'John', age: 25 })

obj = reactive({})

这将清空 obj 对象,并且创建一个新的空对象。但是请注意,在这种情况下,我们创建了一个新的对象,而不是清空原始对象。

以上是清空 Vue3 reactive 的四种方法。但是请注意,这些方法只能清空对象上的属性,不能删除对象本身。如果需要删除对象本身,则需要使用 delete 操作符或重新赋值。

实际使用的有效代码是

let carSafetyProcessForm = reactive({
  id: '',
  accidentProcessingTeam: '',
  accidentAftermathTeam: '',
  accidentMeetingMinutes: '',
  accidentMeetingMinutesPic: '',
  accidentMeetingMinutesSignaturefile: '',
  accidentHandlingNotifications: '',
  accidentHandlingNotificationsPic: '',
  accidentHandlingNotificationsSignaturefile: '',
})
        let ays = Object.keys(carSafetyProcessForm);      //['id','accidentProcessingTeam','accidentAftermathTeam',...]
        ays.map((k)=>{
            carSafetyProcessForm[k] = undefined
        })

像Object.assign(obj, {}),这个语句使用是没有设么效果,也许是我使用方式不对吧。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK