Home > Software design >  Vue 3: v-model and emit
Vue 3: v-model and emit

Time:04-25

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 >
    
    <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 !

CodePudding user response:

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"
 />
  • Related