vue组件之间的访问
1.父组件访问子组件,通过this.$children或this.#refs
this.$children返回一个数组,包含所有的子组件(不推荐使用)
this.#refs通过标签绑定ref使用(推荐使用)
2.子组件访问父组件,通过this.$parent或this.$root
this.$parent返回子组件的上级父组件
this.$root返回当前子组件上的根组件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="constain">
<tone ref='tone'></tone>
<br>
<button @click='showMsg()'>组件访问子组件</button>
</div>
<template id="tone">
<div>
<button @click='showMsg()'>子组件访问组件</button>
</div>
</template>
<script>
const app = new Vue({
el:'#constain',
data:{
msg:'组件'
},
methods:{
showMsg(){
console.log("通过children访问子组件:"+this.$children[0].cmsg); //children返回一个数组,包含组件中包含的所有子组件
console.log("通过refs访问子组件"+this.$refs.tone.cmsg); //通过标签属性绑定ref使用
}
},
components:{
tone:{
template:'#tone',
props:{
da:Number
},
data(){
return{
cmsg:'子组件'
}
},
methods:{
showMsg(){
console.log("通过parent访问父组件"+this.$parent.msg); //访问当前组件的上级组件
console.log("通过parent访问根组件"+this.$root.msg); //访问当前组件的根组件
}
}
}
}
});
</script>
</body>
</html>

浙公网安备 33010602011771号