0

How can I change the prop value of a component and notify these components about the change?

Parent.vue

<script setup>
import Child from './Child.vue'

const finished = ref(false)

function submit() {
    finished.value = true;
}
</script>

<template>
    <Child :open="finished">
    <button @click="submit">Klick</button>
</template>

Child.vue

<template>
    <div v-if="open">Dies ist ein Test.</div>
</template>
  
<script setup>
import { ref } from 'vue'

const props = defineProps(['open'])

const open = ref(props.open)
</script>

When I click on the button, the value changes, but the child component is not notified about it. console.log(open) is still false.

I am using Vue.js version 3 with the composition API.

2 Answers 2

2

You don't need to assign with ref, you can use just props.open in Child.vue.

<template>
  <div v-if="props.open">Dies ist ein Test.</div>
</template>
  
<script setup>
import { ref, defineProps } from 'vue'

const props = defineProps(['open'])
</script>

However, if you want to compute this prop, you can use computed as the first answer from Boussadjra Brahim.

Sign up to request clarification or add additional context in comments.

1 Comment

That was easy. Thank you!
1

There's some conflict in the Child component, you've a prop named open and a ref property with the same name, which in this case give the priority to the ref one, rename the other property to isOpen and define it as computed :

<template>
    <div v-if="isOpen">Dies ist ein Test.</div>
</template>
  
<script setup>
import { computed } from 'vue'

const props = defineProps(['open'])

const isOpen =  computed(()=>props.open)
</script>

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.