繁体   English   中英

子发射不更新父级的 v-model prop 数组

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

我正在使用这个父组件:

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

state.toggles作为道具传递给cms-editor-toolbar子组件:

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

无论出于何种原因emit('update:toggles', toggleAction)只向父级发出第一个toggleAction 对于其他所有更改, state.toggles数组都不会更新。

这个问题的答案中,我尝试使用ref而不是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>

但它什么也没改变。 同样,数组只更新一次,没有连续的动作有任何影响。 我该如何进行这项工作?

编辑:

我已经为子元素内的兄弟元素添加了额外的道具(不是数组),它们不仅被正确发射,而且还触发了array emit 基本上,它似乎将数组保存在子级中,直到由兄弟级发射触发发射,它将完整的数组发送给父级。 不知道这是怎么回事。

我一直在使用错误的方法来检查state.toggles是否已更新。 在一个段落中渲染它通常是可行的,但在这种情况下,它似乎并没有因为任何原因被重新渲染。

像这样在父级中记录数组:

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

表明它确实在更新。 发射器正在工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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