==================================================$children
this.$children[0]. name //获取子组件data
this.$children[0].showMessage() //获取子组件方法
$children的缺点:子组件顺序改变下标会改变原来的代码可能不适用(多子组件情况下)
父组件:
<div id="app">
<cpn></cpn>
<cpn></cpn>
<cpn></cpn>
<button @click="btnClick">获取子组件的对象</button>
</div>
<script>
const app=new Vue({
el:"#app",
components:{cpn},
methods:{
btnClick(){
//方式一、$children(子组件顺序改变时不适用)
for(let c of this.$children){
//获取子组件data
//console.log("子数据"+this.$children[0]. name);
console.log(c.name);
//获取子组件方法
//console.log(this.$children[0].showMessage());
console.log(c.showMessage());
}
}
}
})
</script>
子组件:
<!--子组件-->
<template id="cpn">
<div>我是子组件</div>
</template>
<script>
//子组件
const cpn={
template:`#cpn`,
data(){
return {
name: "我是子组件的数据"
}
},
methods:{
showMessage(){
console.log("子方法showMessage")
}
}
}
</script>
==================================================$parent
this.$parent.name//访问父组件数据
this.$parent.parentCompMethod()//调用父组件方法
$parent不建议在子组件里面使用,复用性不好(一个子组件在多个页面调用,父组件的数据、方法都不一样,与父组件耦合度太高不利于复用)(多父组件情况)
父组件:
<template id="cpn">
<div>
<h2>我是cpn组件</h2>
<ccpn></ccpn>
</div>
</template>
onst cpn={
template:"#cpn",
data(){
return {
name:"我是ccpn组件的父组件cpn"
}
},
components:{
ccpn
},
methods:{
parentCompMethod(){
console.log("我是父组件的方法");
}
}
}
子组件:
<template id="ccpn">
<div>
<h2>我是子组件</h2>
<button @click="btnClick">获取父组件对象</button>
</div>
</template>
const ccpn={
template:"#ccpn",
methods:{
btnClick(){
//子访问父对象$parent
console.log(this.$parent.name)//访问父组件数据
console.log(this.$parent.parentCompMethod())//调用父组件方法
}
}
}
==================================================$root
this.$root.message//访问根组件数据
<!--vue实例-->
<div id="app">
<cpn></cpn>
</div>
<!--子组件-->
<template id="ccpn">
<div>
<h2>我是子组件</h2>
<button @click="btnClick">获取父组件对象</button>
</div>
</template>
//vue实例
const app=new Vue({
el:"#app",
components:{cpn},
data:{
message:"我是vue实例的message"
}
})
const ccpn={
template:"#ccpn",
methods:{
btnClick(){
console.log(this.$root.message)//访问根组件
}
}
}