如何使 Vue 3 对象 属性 具有反应性
How to make a Vue 3 object property reactive
如何制作对象属性reactive
?
当我 运行 下面的代码时,导入的 visible
不会更改为 true
。
导入对象的组件:
<template>
<div class="context">
<span v-if="visible"> test </span>
</div>
</template>
<script>
import { ContextManager } from "./utils.js";
import { ref } from "vue";
export default {
name: "context",
setup() {
const visible = ref(ContextManager.visible);
return { visible };
}
};
</script>
其他向对象添加数据的组件:
const openContext = (e) => {
e.preventDefault();
ContextManager.add({
el: e.target,
items: contextItems
},e );
};
ContextManager 对象:
import { reactive } from "vue";
export const ContextManager = reactive({
context: null,
visible: false,
add(context, e) {
this.visible = true;
}
});
对象的属性不是引用,所以当您提取 visible
属性 时,与原始对象没有任何联系,因为它只是一个普通的布尔值。
toRef
api方法就是为此目的而提供的,以维持这个连接:
Can be used to create a ref for a property on a source reactive object. The ref can then be passed around, retaining the reactive connection to its source property.
导入 toRef
方法并像这样使用它:
import { toRef } from 'vue'
const visible = toRef(ContextManager, 'visible');
如何制作对象属性reactive
?
当我 运行 下面的代码时,导入的 visible
不会更改为 true
。
导入对象的组件:
<template>
<div class="context">
<span v-if="visible"> test </span>
</div>
</template>
<script>
import { ContextManager } from "./utils.js";
import { ref } from "vue";
export default {
name: "context",
setup() {
const visible = ref(ContextManager.visible);
return { visible };
}
};
</script>
其他向对象添加数据的组件:
const openContext = (e) => {
e.preventDefault();
ContextManager.add({
el: e.target,
items: contextItems
},e );
};
ContextManager 对象:
import { reactive } from "vue";
export const ContextManager = reactive({
context: null,
visible: false,
add(context, e) {
this.visible = true;
}
});
对象的属性不是引用,所以当您提取 visible
属性 时,与原始对象没有任何联系,因为它只是一个普通的布尔值。
toRef
api方法就是为此目的而提供的,以维持这个连接:
Can be used to create a ref for a property on a source reactive object. The ref can then be passed around, retaining the reactive connection to its source property.
导入 toRef
方法并像这样使用它:
import { toRef } from 'vue'
const visible = toRef(ContextManager, 'visible');