【问题标题】:Passing the data into component in vuejs将数据传递到 vuejs 中的组件
【发布时间】:2020-11-08 07:42:33
【问题描述】:

我正在尝试将数据从组件中的函数传递到另一个组件。我在谷歌上搜索的所有内容都是关于将数据传递给子父组件,但在我的情况下不是。

这就是我的主要组件的样子

<template>
  <div>
    <h2>Contact List</h2>

    <router-link to="/">Home</router-link>

    <hr />

    <InputForms />

    <List />
  </div>
</template>

我在&lt;InputForms&gt; 组件中传递数据,我想在&lt;List&gt; 组件中接收该数据

这是我在&lt;InputForms&gt; 组件中传递数据的方式

 onSubmit() {
  let numberValidation = this.numbers.map(el => el.value === "");
  let addressValidation = this.addresses.map(el => el.value === "");
  let emailsValidation = this.emails.map(el => el.value === "");

  let len =
    numberValidation.length +
    addressValidation.length +
    emailsValidation.length;

  for (let i = 0; i < len; i++) {
    if (
      numberValidation[i] === true ||
      addressValidation[i] === true ||
      emailsValidation[i] === true ||
      this.title.trim() === ""
    ) {
      return this.$alert("you have an empty space");
      break;
    }
  }
  const newContact = {
    name: this.title,
    number: this.numbers,
    address: this.addresses,
    email: this.emails
  };

  this.$emit("newcontact", newContact);
}

如何在&lt;List&gt; 组件中获取newContact

【问题讨论】:

    标签: vue.js vuejs2 vue-component


    【解决方案1】:

    在包含的组件上为发出的事件注册一个处理程序。

    <InputForms v-on:newContact="onNewContact" />
    

    将发出的数据与包含组件的data 同步。这应该绑定到List 组件。

    <List :newContact="newContact" />
    

    您的包含组件代码

    <template>
      <div>
    
        <InputForms v-on:newContact="onNewContact" />
    
        <List :newContact="newContact" />
    
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          newContact: null
        };
      },
      methods: {
        onNewContact(newContact) {
          this.newContact = newContact;
        }
      }
    }
    </script>
    

    【讨论】:

    • @Bakhodir,我对要演示的答案进行了一些编辑。
    猜你喜欢
    • 1970-01-01
    • 2018-09-12
    • 2017-10-03
    • 2019-03-22
    • 1970-01-01
    • 2020-12-29
    • 2020-12-29
    • 2021-12-07
    • 2020-03-16
    相关资源
    最近更新 更多