1. 前言
我来给你们添蜜啦
之前我们介绍了父传子使用props属性,子传父使用$emit发射自定义函数实现父子组件通信。那么我们有什么方法可以直接在父组件操作子组件的数据或函数、子组件操作父组件的数据或函数吗?下面就通过 $children 、$refs、$parent实现。
有时候我们需要父组件直接访问子组件,子组件直接访问父组件,或者是子组件访问根组件。
- 父组件访问子组件:使用$children或$refs。
- 子组件访问父组件:使用$parent。
2. 父组件访问子组件
2.1 $children
this.$children是一个数组类型,它包含所有子组件对象。
实例:在父组件通过this.$children来获取子组件定义的图片的imgSrc地址:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>vue_learn</title>
<style></style>
</head>
<body>
<template id="component">
<div>
<img :src="imgSrc" />
</div>
</template>
<div class="container" @click="getChild">
<!-- 使用组件 -->
<my-component></my-component>
</div>
<script src="./vue.js"></script>
<script>
// vue实例1
var app1 = new Vue({
el: ".container",
methods: {
getChild: function () {
console.log("子组件数据:", this.$children[0].imgSrc);
},
},
components: {
// 在vue实例注册组件,形成父子关系,局部组件
"my-component": {
template: "#component",
data: function () {
return {
imgSrc:
"https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=272736508,2842806735&fm=26&gp=0.jpg",
};
},
},
},
})