【问题标题】:Vue 2 - how to bind Parent and Child components - with FORM contentsVue 2 - 如何绑定父组件和子组件 - 与 FORM 内容
【发布时间】:2021-03-28 17:28:49
【问题描述】:

这个想法是绑定父组件和子组件,类似于此处显示的示例,使用同步,但使用包含表单字段的对象。

(我目前在子组件上使用监视程序来检测父表单数据中的 Prop 更改,这工作正常,但我猜同步解决方案会更优雅)

单字段示例:

家长

<template>
  <div id="app">
    <h3>Parent Component</h3>
    <ChildComponent :inputData.sync="parentData" />
  </div>
</template>

<script>
import ChildComponent from "./components/ChildComponent.vue";

export default {
  name: "App",
  data: function() {
    return {
      parentData: "my input"
    };
  },
  components: {
    SChildComponent
  }
};
</script>

子组件:

<template>
  <div class="child-component">
    <input
      type="text"
      v-model="inputData"
      @keyup="$emit('update:inputData', inputData);"
    />
  </div>
</template>
<script>
export default {
  name: "ChildComponent",
  props: {
    inputData: String
  }
};
</script>

总结:我正在寻找提交所有字段的表单版本

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    不确定是否能解决您的问题,以下是我的经验:

    1. 使用ref$ref,可以在父组件的子组件上设置ref标签,比如这个例子:
    <div id="app">
        <!-- ref attribute -->
        <child-component ref="child1"></child-component>
        <child-component ref="child2"></child-component>
        <button @click="show">alert child-component count</button>
    </div>
    
    
    // Child component
    Vue.component('child-component', {
        data: function () {
            return {
                count: 20
            };
        },
        methods: {
            getOne: function () {
                this.count++;
            }
        },
        template: '<button @click="getOne">{{ count }}</button>'
    });
    
    // Parent Component
    const vm = new Vue({
        el: '#app',
        data: {},
        methods: {
            show: function () {
    
                // get "count" of child component by $refs 
                console.log(this.$refs.child1.count);
                console.log(this.$refs.child2.count);
            }
        }
    });
    

    它不仅可以获取子组件的特定参数或变量,还可以获取整个子组件。 我希望上述解决方案可以帮助你:)

    【讨论】:

    • 感谢您的努力,一个孩子就足够了,想在一个孩子中使用具有多个表单字段的表单。 :-)
    • 那么,也许你可以使用 event bus 使用 emit 和 on 来获取另一个组件,因为你将使用子组件的 v-model 定义每个表单字段的整个变量,这样你就可以获得改变你想要的。
    猜你喜欢
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多