A
A
Andrew2021-12-28 04:29:18
Vue.js
Andrew, 2021-12-28 04:29:18

How to make a property of an object passed to props reactive (Vue 3)?

I'm tinkering with Vue 3 and I've come across props that are no longer reactive. I understood how to connect reactivity for primitive values, but I still didn’t figure out how to deal with the situation when I pass an object and want to track changes in one of its fields.

The structure is something like this:

<template>
<my-component :prop="prop" />
</template>

<script>

export default {
    data() {
        return {
            prop: {
                key: 'value',
                flag: true
            }
        }
    }
}
</script>


my-component.vue
<template>
     // предположим, что где-то что-то влияет на значение поля flag и мы хотим это здесь отобразить
    <div v-if="flag">Yay, it's a flag!</div>
    <div v-else>I am very sad rn</div>
</template>

<script>

export default {
    props: {
        prop: Object
    },
    setup(props) {
        const prop = ref(props, 'prop')
        const flag = // хрен его знает, что тут делать

        return { flag }
    }
}
</script>

I have tried different manipulations with all possible ref methods (like , ) but without success. const flag = ref(prop, 'flag')const flag = ref(prop.value, 'flag')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GrayHorse, 2021-12-28
@GrayHorse

toRefs

<script setup>
import {toRefs} from "vue";
const props = defineProps({
  name: {
    default: "unknown",
    type: String
  }
});
const {name} = toRefs(props);
</script>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question