Code前端首页关于Code前端联系我们

Vue2.x中的亲子沟通

terry 2年前 (2023-09-08) 阅读数 143 #Vue

这里我引用我之前写的一个项目作为例子

先贴上代码

list.vue 组件

父组件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>

 

通过道具从父亲到儿子,通过$emit子从父亲到儿子

在父组件中查看子组件,然后通过参数将数据传递给子组件。如果子组件需要返回数据,父组件可以通过自定义事件的形式接收数据。

如下图所示,父组件将FriendList传递给子组件,子组件用props中的friendList接收然后显示。当点击li的时候,子组件通过$emit组件将当前点击的li的用户名传递给父组件,父组件通过getcontact接收。

image-20210517200059214image-20210517200059214

image-20210517200215929image-20210517200215929

注意:父组件中@set-contact中的set-contact必须与子组件中this.$emit("set-contact", this.friendList[index])中的set-contact保持一致。

在子组件中使用 props 来接受从父组件传递的相当于形式参数的值。你也可以自己定义接收参数的类型,例如:

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

印象

image-20210517201148120image-20210517201148120

当我们点击猫这样的元素时,就会出现控制台,并显示子组件返回的数据。

image-20210517201241762image-20210517201241762

通过$refs

在父组件中的子组件中使用 ref 声明,ref 指向子组件的实例

image-20210517210505296image-20210517210505296

然后您可以以 this.$refs.name 的形式调用子组件方法。

如下所示,在父组件内部调用this.$refs.friends就可以看到vue实例对象。该对象是 list.vue 的实例,您可以将 ​​ 传递给 。 $refs.friends.getList(this.friendList) 调用子组件方法并将参数 this.friendList 传递给子组件。

image-20210517204207913image-20210517204207913

image-20210517204518369image-20210517204518369

image-20210517204600947image-20210517204600947

通过 $parent 和 $children

可以通过 $parent 访问父组件,可以通过 $children 访问子组件。用法和前两者类似,主要是一些细节

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

在下图中,您可以看到 $parent 和 $children 返回一个对象。如果需要引用组件方法属性,则需要 this。 $父母。方法之类的。 $孩子们[0]。方法

image-20210517215219629image-20210517215219629

image-20210517215002853image-20210517215002853

image-20210517214741181image-20210517214741181

这个用的比较少,我主要用上面两个

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门