vue3: const obj = reactive({}); obj = reactive({a:1}); 页面不渲染内容
时间: 2024-02-22 21:56:41 浏览: 16
在 Vue 3 的 Composition API 中,使用 `reactive` 函数创建的对象是响应式的,这意味着当对象的属性被修改时,相关的组件会自动重新渲染。但是,当你将一个新的对象赋值给一个使用 `reactive` 函数创建的对象时,这个对象就会丢失响应式。
在你的示例中,`const obj = reactive({})` 创建了一个空的响应式对象 `obj`。但是,当你执行 `obj = reactive({a:1})` 时,你将一个新的经过 `reactive` 函数处理的对象赋值给了 `obj`。虽然这个新对象是响应式的,但是它并不是之前的 `obj`,因此相关的组件不会重新渲染。
如果你想修改一个使用 `reactive` 函数创建的响应式对象的属性,应该直接修改它的属性而不是将一个新的对象赋值给它。如果你需要替换整个对象,可以使用 `Object.assign` 或者 `spread` 运算符来将新旧对象的属性合并到一起。
例如,你可以这样来修改 `obj` 的属性:
```
// 修改属性
obj.a = 1
// 合并对象
obj = Object.assign(obj, {a: 1})
// 或者
obj = {...obj, a: 1}
```
这样做会触发组件的重新渲染,并且 `obj` 仍然保持着响应式。
相关问题
vue3: const obj = reactive({})
这是一个使用 Vue 3 的 Composition API 中的 `reactive` 函数来创建响应式对象的示例。`reactive` 函数接收一个普通对象作为参数,返回一个经过处理的响应式对象,可以在模板和组件中使用。
在上述示例中,`const obj = reactive({})` 创建了一个空的响应式对象 `obj`。可以通过 `obj` 对象添加属性或修改属性的值,这些变化将会自动触发重新渲染相关的组件。例如,可以通过 `obj.name = 'Bob'` 来给 `obj` 对象添加一个名为 `name` 的属性,并给其赋值为 `'Bob'`。
vue3 reactive toRaw
`toRaw` is a function in Vue 3's `@vue/reactivity` package that returns the original raw reactive object of a proxy created by the `reactive` function.
In Vue 3, when you use the `reactive` function to create a reactive object, it wraps the original object in a proxy. The `toRaw` function allows you to access the original raw object from the proxy.
Here's an example usage:
```javascript
import { reactive, toRaw } from 'vue';
const obj = reactive({ foo: 'bar' });
const proxy = toRaw(obj);
console.log(proxy.foo); // Output: bar
console.log(obj === proxy); // Output: false
```
In the example above, the `obj` is a reactive object created using `reactive`. When we call `toRaw(obj)`, it returns the original raw object, which is equivalent to `{ foo: 'bar' }`. Note that `obj` and `proxy` are not the same object, but they have the same values.
This function can be useful in certain scenarios where you need to access the original object or perform operations that are not supported on proxies but are supported on raw objects.