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
Add a ment  | 

1 Answer 1

Reset to default 4

The 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