如何使用子组件的 prop 更新父 v-model? [英] How to update parent v-model using child components' prop?

查看:45
本文介绍了如何使用子组件的 prop 更新父 v-model?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的父组件有以下子组件:

My parent component has the following child component:

<editor :editorBody="formData.englishBody"></editor>

我的父组件有以下数据:

My parent component has the following data:

data () {
  return {
    // allContent: null,
    formData: {
      englishTitle: '',
      nepaliTitle: '',
      englishBody: '',
      nepaliBody: '',
      activeInactive: false,
      userId: null
    },
    rowId: null
  }
}

我的子组件有自己的v-model,我正在从父组件向子组件v-model提供道具.

My child component has its own v-model, I am feeding props from parent to the child components v-model.

<q-editor v-model="editorBody"></q-editor>

formData.englishBody 是父组件数据.我想使用 editor 子组件更新 formData.englishBody.editor 子组件是一个 textarea.基本上,我想将孩子的 v-model 链接到父母数据.

The formData.englishBody is a parent component data. I want to update formData.englishBody using the editor child component. editor child component is a textarea. Basically, I want to link child's v-model to parents data.

推荐答案

您需要确保每当 组件更新 editorBody 值时,它不直接分配给道具,因为这是不允许的(道具是从父级到子级的单向),而是需要发出一个具有新值的事件.

You need to make sure that whenever the <editor> component updates the editorBody value, it does not assign to the prop directly because this is not allowed (props are one-way from parent to child), instead it needs to emit an event with the new value.

约定是使用新值发出名为 update:editorBody 的事件.然后父组件可以侦听该事件并更新 formData.englishBody 以响应该事件:

The convention is to emit an event named update:editorBody with the new value. Then the parent component can listen for that event and update formData.englishBody in response to that event:

<editor
  :editorBody="formData.englishBody"
  @update:editorBody="formData.englishBody = $event"
>

这可以简化为:

<editor :editorBody.sync="formData.englishBody">

这是一个特殊的双向绑定.

记住, 必须发出 update:editorBody 事件!这意味着您不能在 组件模板中使用 v-model="editorBody".

Remember, <editor> must be emitting the update:editorBody event! This means you cannot use v-model="editorBody" inside the <editor> component template.

在您的 组件中,更改以下内容:

In your <editor> component, change this:

<q-editor v-model="editorBody">

对此(假设 没有自定义v-model):

to this (assuming <q-editor> didn't customize v-model):

<q-editor
  :value="editorBody"
  @input="$emit('update:editorBody', $event)"
>

请参阅文档以了解更多信息-深入的解释和例子.

Consult the docs for a more in-depth explanation and examples.

这篇关于如何使用子组件的 prop 更新父 v-model?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆