Father visit the son
children
It is not recommended because too many components or changes can cause source code confusion and make it difficult to operate
<div id="app">
<div>
<cpns></cpns>
<cpns></cpns>
<cpns></cpns>
</div>
</div>
<template>
<div id="cpn">
<h2>The text</h2>
</div>
</template>
<script>
const app = new Vue({
el:'#app'.data: {},components: {cpns: {template:"#cpn".data(){
name:'I'm the name of the child component'}}}, mounted: {console.log(this.$children) // The Vuecomponent object will be printed out as an array, and the subscript value will be used to manipulate the subcomponent;
console.log(this.$children[0].name) // Values the name variable in the first child}})</script>
Copy the code
refs
It is recommended to use ref
<div id="app">
<div>
<cpns ref="aaa"></cpns>
<cpns ref="bbb"></cpns>
<cpns ref="ccc"></cpns>
</div>
</div>
<template>
<div id="cpn">
<h2>The text</h2>
</div>
</template>
<script>
const app = new Vue({
el:'#app'.data: {},components: {cpns: {template:"#cpn".data(){
name:'I'm the name of the child component'}}}, mounted: {console.log(this.$refs) // All Vuecomponent objects will be printed out as objects;
console.log(this.$refs.aaa.name) // Values the name variable in the first child}})</script>
Copy the code
Child access to the father
parent
<div id="app">
<div>
<cpns ref="aaa"></cpns>
<cpns ref="bbb"></cpns>
<cpns ref="ccc"></cpns>
</div>
</div>
<template>
<div id="cpn">
<h2>The text</h2>
</div>
</template>
<script>
const app = new Vue({
el:'#app'.data: {},components: {cpns: {template:"#cpn".data(){
name:'I'm the name of the child component'}, mounted: {console.log(this.$parent) // Information about the parent component is printed}}}})</script>
Copy the code
root
<script>
const app = new Vue({
el:'#app'.data: {},components: {cpns: {template:"#cpn".data(){
name:'I'm the name of the child component'}, mounted: {console.log(this.$root) // The information in the Vue instance is printed}}}})</script>
Copy the code
Try not to directly manipulate the parent component and root component values in the child component to avoid unnecessary trouble