这里我引用我之前写的一个项目作为例子
先贴上代码
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接收。
注意:父组件中@set-contact中的set-contact必须与子组件中this.$emit("set-contact", this.friendList[index])中的set-contact保持一致。
在子组件中使用 props 来接受从父组件传递的相当于形式参数的值。你也可以自己定义接收参数的类型,例如:
// 把props: ["friendList"]换成
props: {
friendList: {
type: Array,
}
}
印象
当我们点击猫这样的元素时,就会出现控制台,并显示子组件返回的数据。
通过$refs
在父组件中的子组件中使用 ref 声明,ref 指向子组件的实例
然后您可以以 this.$refs.name 的形式调用子组件方法。
如下所示,在父组件内部调用this.$refs.friends就可以看到vue实例对象。该对象是 list.vue 的实例,您可以将 传递给 。 $refs.friends.getList(this.friendList) 调用子组件方法并将参数 this.friendList 传递给子组件。
通过 $parent 和 $children
可以通过 $parent 访问父组件,可以通过 $children 访问子组件。用法和前两者类似,主要是一些细节
$parent 返回一个对象对象,$children 返回一个数组对象
在下图中,您可以看到 $parent 和 $children 返回一个对象。如果需要引用组件方法属性,则需要 this。 $父母。方法之类的。 $孩子们[0]。方法
这个用的比较少,我主要用上面两个
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。