父访问子
1.$children默认是一个空数组
2.$refs,对象类型,默认是一个空对象(要给子组件一个ref属性)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<cpn ref="reference"></cpn>
<button @click = 'btnClick'>按钮</button>
</div>
</body>
<template id="cpn">
<div>
子组件
</div>
</template>
<script src="../js/vue.min.js"></script>
<script>
var app=new Vue({
el:'#app',
data:{
},
methods:{
btnClick(){
console.log(this.$children);
this.$children[0].showMessage()
// 1.$children 默认是一个数组
console.log(this.$children[0].name);
// 2.$refs =>对象类型,默认是一个空对象
console.log(this.$refs.reference.name);
}
},
components:{
cpn:{ //子组件
template:"#cpn",
methods: {
showMessage(){
console.log("showMessage");
},
},
data() {
return {
name:'我是子组件的name'
}
},
}
}
});
</script>
<html>
子访问父
1.$parent访问父组件
2.$root访问根组件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<cpn ></cpn>
</div>
</body>
<template id="cpn">//子组件
<div>
<h2>我是cpn组件</h2>
<ccpn></ccpn>
</div>
</template>
<template id="ccpn">//孙子组件
<div>
cpn的子组件
<button @click = 'btnClick'>按钮</button>
</div>
</template>
<script src="../js/vue.min.js"></script>
<script>
var app=new Vue({
el:'#app',
data:{
message:'哈哈'
},
methods:{
},
components:{
cpn:{//子组件
template:"#cpn",
methods: {
},
data() {
return {
name:"666"
}
},
components:{
ccpn:{ //孙子组件
template:"#ccpn",
methods: {
btnClick(){
// 1.访问父组件
console.log(this.$parent.name);//666 他的父组件就是cpn
// 访问根组件 $root
console.log(this.$root.message); //哈哈
}
},
}
}
}
}
});
</script>
<html>