Home > Net >  Changing prop of component in vue.js with composition API
Changing prop of component in vue.js with composition API

Time:08-30

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.

CodePudding user response:

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.

CodePudding user response:

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

  • Related