【问题标题】:Vue 3 using v-model as props instead of :prop and @emitVue 3 使用 v-model 作为 props 而不是 :prop 和 @emit
【发布时间】:2021-09-04 01:17:56
【问题描述】:

所以我已经阅读了几次this 文章,据我了解,我可以使用 v-model 而不是 props,将值从父组件传递给子组件,并在 prop 的值为在子节点中进行修改,从而以更少的代码获得双向绑定(无需在父节点中捕获已发出的事件)。但是它并没有按照我认为的方式工作。

这是我的代码:

<template>
  <!-- This is ParentComponent.vue -->
  <ChildComponent v-model:documents="user.documents" />
</template>
<script lang="ts">
  // This is ParentComponent.vue
  import { Vue, Options } from 'vue-class-component';
  import UserClass from '@/some/place/UserClass';
  import ChildComponent from '@/components/ChildComponent.vue';

  @Options({
    components: {
      ChildComponent,
    }
  })
  export default class ParentComponent extends Vue {
    // Local state.
    user: UserClass = new UserClass();
  }
</script>
<template>
  <!-- This is ChildComponent.vue -->
  <section v-for="document in documents" :key="document.id">
    {{ document.name }}
    <button @click="remove(document.id)">Delete document</button>
  </section>
</template>
<script lang="ts">
  // This is ChildComponent.vue
  import { Vue, Options } from 'vue-class-component';
  import IDocument from '@/interfaces/IDocument';

  @Options({
    props: ['documents'],
    emits: ['update:documents'],
  })
  export default class ChildComponent extends Vue {
    // Types.
    documents!: IDocument[];

    // Methods.
    remove(documentId: string): void {
      this.documents = this.documents.filter((document) => document.id !== documentId);
    }
  }
</script>

我希望当单击子组件内的按钮时,它应该触发“remove()”方法,而不是直接向 this.documents 分配新值,它应该发出 update:documents 事件,反过来,它应该被父组件捕获并用于更新父组件的本地状态。

但相反,我收到以下警告:

试图改变道具“文档”。道具是只读的。

还有以下错误:

未捕获的 TypeError:代理集处理程序为属性“文档”返回 false

我哪里错了?提前致谢。

【问题讨论】:

    标签: typescript vuejs3 vue-class-components


    【解决方案1】:

    我想我错过了 v-model 工作原理的一个重要特征。我假设像这样使用 v-model 传递值

    <ChildComponent v-model:documents="user.documents" />
    

    当 ChildComponent 中的文档属性值发生更改时,将自动发出 update:documents 事件。但是您似乎仍然需要手动发出此事件,如下所示:

    <script lang="ts">
      // This is ChildComponent.vue
      import { Vue, Options } from 'vue-class-component';
      import IDocument from '@/interfaces/IDocument';
    
      @Options({
        props: ['documents'],
        emits: ['update:documents'],
      })
      export default class ChildComponent extends Vue {
        // Types.
        documents!: IDocument[];
    
        // Methods.
        remove(documentId: string): void {
          // The user.documents in the ParentComponent would be overriden with filtered array, generated here in the child.
          this.$emit('update:documents',  this.documents.filter((document) => document.id !== documentId));
        }
      }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      • 2020-09-19
      • 2020-09-26
      • 2021-09-15
      • 2022-08-20
      • 2021-12-30
      相关资源
      最近更新 更多