How to make an object passed as a prop in Vue 3 reactive?

Viewed 204

I need to reactively change my component when a field in passed object changes.

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

<script>

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

mycomponent.vue

<template>
    <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>
  • Don't know what to do here, prop.flag, prop.value.flag doesn't work.

I also tried something like const flag = ref(prop, 'flag') and then flag.value, or even const flag = req(prop.value, 'flag'), but no luck.

2 Answers

Props are accessible and reactive in components should you declare them. Since you haven't, they won't be available.

For example, this is all you need:

<template>
  <div v-if="prop.flag">Yay, it's a flag!</div>
  <div v-else>I am very sad rn</div>
</template>

<script>
export default {
  props: {
    prop: Object
  }
}
</script>

Just use toRef or toRefs

<template>
    <div v-if="flag">Yay, it's a flag!</div>
    <div v-else>I am very sad rn</div>
</template>

<script>
import { toRefs, toRef } from 'vue';
export default {
    props: {
        prop: Object
    },
    setup(props) {
        const { prop } = toRefs(props);
        //alternative
        const prop = toRef(props, 'prop');
        const flag = // *

        return { flag }
    }
}
</script>
Related