Hannes A
Hannes A

Reputation: 97

How to make a Vue 3 object property reactive

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 component 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;
    }
});

Upvotes: 5

Views: 6240

Answers (1)

Dan
Dan

Reputation: 63059

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');

Upvotes: 4

Related Questions