父访问子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<cpn></cpn>
<cpn ref="aaa"></cpn>
<cpn></cpn>
<button @click="btnClick">按钮</button>
</div>
<template id="cpn">
<div>
<h2>我是子组件</h2>
</div>
</template>
<script src="../../js/vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data: {
},
components:{
cpn: {
template: '#cpn',
data() {
return {
name: "我是子组件的name"
}
},
methods: {
showMessage() {
console.log('我是子组件')
}
},
}
},
methods: {
btnClick() {
// 父访问子方法:$children(一般不使用这种方法,因为组件数量在变化,用下标容易发生混乱)
// console.log(this.$children),
// this.$children[0].showMessage()
// for(item of this.$children){
// console.log(item.showMessage())
// }
// $refs,需在使用父组件时定义其键名,一般使用这个
console.log(this.$refs.aaa.name,this.$refs.aaa.showMessage());
// console.log(this.$refs.aaa.showMessage())
}
},
})
</script>
</body>
</html>
子访问父
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<cpn></cpn>
</div>
<template id="cpn">
<div>
<h2>我是子组件</h2>
<ccpn></ccpn>
</div>
</template>
<template id="ccpn">
<div>
<h2>我是孙组件</h2>
<button @click="btnClick">按钮</button>
</div>
</template>
<script src="../../js/vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data: {
name: "我是顶层的name"
},
components:{
cpn: {
template: '#cpn',
data() {
return {
name: "我是子组件的name"
}
},
components:{
ccpn: {
template: '#ccpn',
methods: {
btnClick() {
// $parent访问的是组件上一层的属性
console.log(this.$parent.name),
// $root访问的是顶层组件的属性,两种方法都很少用,因为要避免耦合
console.log(this.$root.name)
}
},
}
}
}
},
})
</script>
</body>
</html>