【问题标题】:Vue parent-child emit function is breaking v-model bindingVue 父子发出函数正在破坏 v-model 绑定
【发布时间】:2020-05-13 03:38:03
【问题描述】:

正在修复其他人代码中的错误,因此我试图限制我必须在此处更改的内容。

似乎当我使用 $emit 功能在子组件和父组件之间运行函数时,我的组件中丢失了 v-model 绑定。

有一个父组件:

父组件.vue

<template>
    <child-component v-bind:items="this.items"
                     v-on:event_child="this.eventUpdater">
    </child-component>
<template>
<script>
    import ChildComponent from './ChildComponent.vue';
    export default {
        components: {
            'child-component': ChildComponent
        },
        methods: {
            getItemDetails() {
                //...ajax request that loads item details for page.
            },
            eventUpdater: function(id) {
                this.getItemDetails();
            }
        }
    }
</script>

然后,有一个子组件:

ChildComponent.vue

<template>
    <div v-for="item in items">
        <input v-model="item.itemId">
    </div>
    <button v-on:click="updateItems">update</button>
</template>
<script>
    export default {
        props: ['items'],
        methods: {
            updateItems() {
                //...ajax call that updates items.
                this.emitWhat();
            },
            emitWhat: function () {
                this.$emit('event_child');
            }
        }
    }
</script>

更新我的初始项目(更新正常)后,我去更新另一个项目,似乎该项目的 v-model 不起作用。 $emit 功能是否在初始加载后破坏了 v-model 绑定?我该如何解决这个问题?

【问题讨论】:

  • 我没有看到事件总线,它在哪里
  • @Ifaruki - 我误用了这个词。我把它拿出来了。我很抱歉。

标签: javascript vue.js components parent-child emit


【解决方案1】:

你正在使用这个:

    <child-component v-bind:items="this.items"
                 v-on:event_child="this.eventUpdater">

但应该使用这个:

<child-component v-bind:items="items"
    v-on:event_child="eventUpdater">

删除this.

我也没有在父组件中找到items 作为data 属性。

更新。

另外,如果你在eventUpdater: function(id) 方法中定义id 参数,你应该像这样emit 它:

<template>
    <div v-for="item in items">
        <input v-model="item.itemId">
    </div>
    <button v-on:click="updateItems(item.itemId)">update</button>
</template>

        updateItems(id) {
            //...ajax call that updates items.
            this.emitWhat(id);
        },
        emitWhat: function (id) {
            this.$emit('event_child', id);
        }

更新.2

您在item.itemId 上还有 v-model,这可能是个问题:

<input v-model="item.itemId">

您可以考虑像这样将v-model 绑定到newItems

<input v-model="newItems[itemId]">

data(){
  return {
    newItems: [],
    //...
  };
}

【讨论】:

    猜你喜欢
    • 2023-02-03
    • 1970-01-01
    • 2018-11-02
    • 2020-10-29
    • 2020-07-15
    • 2021-11-17
    • 2020-06-27
    • 2020-01-23
    • 2021-07-01
    相关资源
    最近更新 更多