【问题标题】:Sync vue component form field and data value with prop sent in by vue parent component将vue组件表单字段和数据值与vue父组件传入的prop同步
【发布时间】:2020-03-07 16:41:39
【问题描述】:

我有一个谷歌地图的 vue 组件,用户可以在地图上绘制形状。在 Google Maps 组件中,我正在导入另一个处理表单提交的“NewProperty”组件。

因此,用户会先在地图上绘制一个形状,然后再填写几个表单字段。我想将 Google Maps 组件中的形状区域(英亩)发送到 NewProperty 组件并与表单一起提交。

如果英亩属性发生变化,如何自动更新 NewProperty 组件中的表单字段和数据属性?我将一个英亩的道具传递给 NewProperty 组件。我可以看到 NewProperty 组件中的道具值发生变化,但我不知道如何制作它,因此道具也会更新数据属性。我可以将道具绑定到字段值,但我还需要它更新数据属性“form.acres”。形状完成后,在提交表单之前,我想允许用户在需要时更改面积。

如果NewProperty组件的sn-p如下:

<template>
  <form>
     <input type="number" name="acres" :value="acres"        
     @input="form.acres = $event.target.value">
 </form>
</template>

<script>
    export default {
        name: "NewProperty",
        props: ['acres'],
        data() {
            return {
                form: new Form({
                    acres: '',
                })
            }
        }
    }
</script>

任何想法,我如何使 3 个部分(道具、表单字段和数据属性)保持同步?我只需要父子之间的沟通,不需要双向。

【问题讨论】:

  • 什么是Form
  • @Phil,我的错,我删除了很多行以缩短这篇文章。

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

找到了一种解决方案,使用watch

watch: {
    acres: function(newVal, oldVal) {
        this.form.acres = newVal;
    }
},

或 ES6 风格:

watch: {
    acres(newVal, oldVal) {
        this.form.acres = newVal;
    }
},

感谢这篇文章:How to listen for 'props' changes

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 2020-09-25
    • 2017-08-19
    • 2021-04-23
    相关资源
    最近更新 更多