关于javascript:Vue2x中父子组件通信

在这里就援用之前写的我的项目,举个栗子

先贴上代码

list.vue组件

<template>
  <div class="list">
    <ul v-for="(friend, i) in friendList">
      <li @click="setContact(i)"> 
        <p class="name">{{friend.username}}</p>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  props: ["friendList"],
  methods: {
  // 创立一个setContact办法,把以后点击的名称传给父组件
    setContact(index) {
      this.$emit("set-contact", this.friendList[index]);
    },
  // 创立一个办法,获取参数
    getList(list) {
      console.log(list);
      console.log(typeof this.$parent);// object
    },
  },
};
</script>

父组件chat.vue

<template>
  <div id="chat">
        <user-list :friendList="this.friendList" @set-contact="getcontact"ref="friends"></user-list>
  </div>
</template>

<script>
import UserList from "../../components/chat/list";
export default {
  data() {
    return {
      friendList: [
        {
          username: "tom"
        },
        {
          username: "cat"
        },
        {
          username: "dog"
        }
      ],
    };
  },
  components: {
    UserList
  },
   mounted() {
    console.log(this.$refs.friends);
    this.$refs.friends.getList(this.friendList);
    console.log(this.$children instanceof Array); // true
    console.log(this.$children);  
  },
  methods: {
    // 接管子组件返回的数据
    getcontact(index) {
      console.log(index);
    },
  },
};
</script>

通过props父传子,通过$emit子传父

在父组件中援用子组件,再把数据通过参数传给子组件,如果须要子组件在返回数据的话,父组件能够通过自定义事件的模式,接收数据。

如下图,父组件通过friendList传给子组件,子组件用props中的friendList接管,而后显示进去,当点击某个li的时候,子组件就通过$emit把以后点击li的username传给父组件,父组件通过getcontact接管。

留神:父组件中@set-contact中的set-contact,必须与子组件中this.$emit(“set-contact”, this.friendList[index])中set-contact统一。

在子组件中利用props接管父组件中传过来的值,相当于形参,也能够本人定义接管参数类型,比方这样:

// 把props: ["friendList"]换成
props: {
    friendList: {
      type: Array,
    }
}

效果图

当咱们点击某个item时,比方cat,控制台就会显示,就会显示子组件返回的数据了。

通过$refs

通过在父组件中的子组件中申明ref,那么这个ref就指向子组件实例

接下来,就能够通过this.$refs.名称 的模式调用子组件的办法。

如下图,通过在父组件中的mounted中调用this.$refs.friends能够看到一个vue实例对象,这个对象就是list.vue实例,而且能够通过*this*. $refs.friends.getList(this.friendList)模式调用子组件的办法,并把参数this.friendList传给子组件。

通过$parent和 $children

通过$parent能够拜访父组件,通过 $children能够拜访子组件,用法跟后面两种大同小异,次要就是一些细节的问题

$parent返回一个object对象, $children返回的是一个数组对象

通过下图,能够看到$parent和 $children返回的是一个对象,须要援用组件办法属性的话,须要this. $parent.办法和this. $children[0].办法

这个用的比拟少,我次要用的是下面两个

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理