简体   繁体   中英

Child emit does not update v-model prop Array of parent

I'm using this parent component:

<template>
  <div id="cms-custom-editor" class="cms-custom-editor">
    <cms-editor-toolbar v-model:toggles="state.toggles"/>
    <div class="content">Toggle Buttons: {{ state.toggles }}</div>
  </div>
</template>


<script setup>
import CmsEditorToolbar from './cms-editor-toolbar.vue'
import {reactive, ref} from "vue";

const state = reactive({
    toggles: [],
})
</script>

to pass down state.toggles as a prop to the cms-editor-toolbar child component:

<template>
  <div id="cms-editor-toolbar" class="cms-editor-toolbar">
    <button @click="toggleButton"></button>
  </div>
</template>


<script setup>

const props = defineProps({
    toggles: Array,
})

const emit = defineEmits(['update:toggles'])

const toggleButton = () => {
    // ... logic to determine toggleAction
    console.log(toggleAction) // logs correct toggleAction
    emit('update:toggles', toggleAction) //emits only first toggleAction and no other
}

</script>

For whatever reason emit('update:toggles', toggleAction) only emits the first toggleAction to the parent. For every other change, the state.toggles array is not updated.

From the answer in this question , I've tried using ref instead of reactive :

<template>
  <div id="cms-custom-editor" class="cms-custom-editor">
    <cms-editor-toolbar v-model:toggles="toggles"/>
    <div class="content">Toggle Buttons: {{ toggles }}</div>
  </div>
</template>


<script setup>
import CmsEditorToolbar from './cms-editor-toolbar.vue'
import {reactive, ref} from "vue";

const toggles = ref([1,2,3])
</script>

but it changes nothing. Again the array is only updated once and no consecutive action has any effect. How do I make this work?

Edit:

I've added additional props (not arrays) to sibling elements inside the child, which not only are emitted correctly, but also trigger all actions of the array emit . Basically it seems to save the array inside the child until the emit is triggered by a sibling emit, which sends the complete array to the parent. No idea how this is happening.

I've been using the wrong method to check if state.toggles is updated. Rendering it in a paragraph usually works, but in this case it doesn't seem to be rerendered for whatever reason.

Logging the array inside the parent like so:

setInterval(function(){
    console.log(state.toggles)
}, 1000);

shows that it is indeed updating. The emits are working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM