Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue 3: v-model and emit

I'm trying to use Vue3 two-way biding with v-model, but my emit() doesn't update the parent value. Could you please tell me where I'm wrong? Thank you!

Parent looks like:

<template>
  <div class="card">
    
    <LearnersTable
        v-model:toActivate="toActivate"
      />
      <!-- To control if this is being updated -->
      {{ toActivate.length }}


  </div>
</template>



<script setup>
[...]

// List of person to activate
const toActivate = [];

</script>

And Children (LearnersTable) looks like:

<template>
    [...]

    <tr v-for="row in rows" :key="row.id"  >
        <span>
            <Toggle v-model="row.enabled" @change="onChangeActivate(row)"/>
        </span>
    </tr>
    [...]

</template>

<script setup>
const props = defineProps({
  
  toActivate: {
    type: Array,
    default: () => [],
  },
});

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

const {
  toActivate,
} = toRefs(props);


function onChangeActivate(row) {

  if (row.enabled === true) {
    toActivate.value.push(row);
  }
  emit('update:toActivate', toActivate.value);
}

</script>

I'm omitting a little bit of code here. But the problem is that my emit doesn't work, I don't get the toActivate value updated in the parent.

Thank you !

like image 603
David Martins Avatar asked Nov 28 '25 02:11

David Martins


1 Answers

Try to make it reactive:

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

// List of person to activate
const toActivate = ref([]);

</script>

and

<LearnersTable
    v-model:to-activate="toActivate"
 />
like image 111
Nikola Pavicevic Avatar answered Nov 29 '25 14:11

Nikola Pavicevic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!