Home > Blockchain >  Vue.js composition API <script setup> - how to two-way bind props
Vue.js composition API <script setup> - how to two-way bind props

Time:10-04

I am struggling to find a way how to create two-way props binding between parent and child components using Vue.js3. Below you can find an example of my code. Unfortunately, the "emit" function does nothing at this point. Thank you for your help.

ParentComponent.vue

<template>
    <child-component :loading="isChildLoading">
    {{ isChildLoading ? 'Child component is loading' : 'Child component is NOT loading' }}
</template>

<script setup>
import {ref} from "vue";
import ChildComponent from 'ChildComponent';

const isChildLoading = ref(false);
</script>

ChildComponent.vue

<script setup>
import {defineProps, defineEmits, onMounted} from "vue";

const props = defineProps({
    loading: Boolean
});

const emit = defineEmits(['update:loading']);

onMounted(() => {
    emit('update:loading', true)

    //After some kind of XMLHttpRequest request set loading to 'false'
    setTimeout(() => {
        emit('update:loading', false)
    }, 5000);
});
</script>

CodePudding user response:

The emit does nothing because you are not listening for the event. You need to do something like this:

 <child-component :loading="isChildLoading" @update:loading="isChildLoading = $event">

You can also setup v-model binding, but it is probably not the correct way here: https://vuejs.org/guide/components/events.html#usage-with-v-model

Btw.: You don't need to import defineProps or defineEmits since those are compiler macros and automatically available inside the <setup setup> block (https://vuejs.org/api/sfc-script-setup.html#defineprops-defineemits)

  • Related