父訪問(wèn)子:
<!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()?{
??????????//?父訪問(wèn)子方法:$children(一般不使用這種方法,因?yàn)榻M件數(shù)量在變化,用下標(biāo)容易發(fā)生混亂)
??????????//?console.log(this.$children),
??????????//?this.$children[0].showMessage()
??????????//?for(item?of?this.$children){
??????????//???console.log(item.showMessage())
??????????//?}
??????????//?$refs,需在使用父組件時(shí)定義其鍵名,一般使用這個(gè)
??????????console.log(this.$refs.aaa.name,this.$refs.aaa.showMessage());
??????????//?console.log(this.$refs.aaa.showMessage())
????????}
??????},
????})
??</script>
</body>
</html>
子訪問(wèn)父
<!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訪問(wèn)的是組件上一層的屬性
??????????????????console.log(this.$parent.name),
??????????????????//?$root訪問(wèn)的是頂層組件的屬性,兩種方法都很少用,因?yàn)橐苊怦詈?/p>
??????????????????console.log(this.$root.name)
????????????????}???????
??????????????},
????????????}
??????????}
????????}
??????},
????})
??</script>
</body>
</html>