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

9次阅读

共计 1898 个字符,预计需要花费 5 分钟才能阅读完成。

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

先贴上代码

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]. 办法

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

正文完
 0