admin管理员组文章数量:1406444
How can I make an object property reactive
?
When I run the code below, the imported visible
doesn't change to true
.
Component that imports the object:
<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>
Other ponent that adds data to the object:
const openContext = (e) => {
e.preventDefault();
ContextManager.add({
el: e.target,
items: contextItems
},e );
};
ContextManager object:
import { reactive } from "vue";
export const ContextManager = reactive({
context: null,
visible: false,
add(context, e) {
this.visible = true;
}
});
How can I make an object property reactive
?
When I run the code below, the imported visible
doesn't change to true
.
Component that imports the object:
<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>
Other ponent that adds data to the object:
const openContext = (e) => {
e.preventDefault();
ContextManager.add({
el: e.target,
items: contextItems
},e );
};
ContextManager object:
import { reactive } from "vue";
export const ContextManager = reactive({
context: null,
visible: false,
add(context, e) {
this.visible = true;
}
});
Share
Improve this question
edited Mar 6, 2021 at 10:57
Dan
63.2k18 gold badges111 silver badges119 bronze badges
asked Mar 6, 2021 at 10:33
Hannes AHannes A
1074 silver badges13 bronze badges
1 Answer
Reset to default 4The object's properties are not refs, so when you extract the visible
property, there's no connection remaining to the original object, because it's just a vanilla boolean.
The toRef
api method is provided for this purpose, to maintain this connection:
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.
Import the toRef
method and use it like:
import { toRef } from 'vue'
const visible = toRef(ContextManager, 'visible');
本文标签: javascriptHow to make a Vue 3 object property reactiveStack Overflow
版权声明:本文标题:javascript - How to make a Vue 3 object property reactive - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745010227a2637506.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论