30 . 父子组件的访问方式: $children 和 $refs
我们知道 父子组件之间的通讯 很烦对吧,所以现在有新方法:
父组件直接访问子组件中的对象:
2种方法 : 1: $children,2: $refs
有以下代码:
<body> <template id="cpn"> <div>不断奋起,直到羔羊变雄狮。</div> </template> <div id="app"> <v-cpn></v-cpn> </div> <script src="js/vue.js"></script> <script> const app = new Vue({ el:"#app", components:{ 'v-cpn':{ template:"#cpn", methods:{ show(){ console.log("cpn子标签 - show方法"); } } } } }) </script>
所以我们先尝试打印 this.$children 看下出来什么:
加个button ,然后点击时候 打印 即:
<body> <template id="cpn"> <div>不断奋起,直到羔羊变雄狮。</div> </template> <div id="app"> <v-cpn></v-cpn> <!-- 这里加Button 然后点击事件父组件中打印 this.$children --> <button @click="showChildren">点击查看$children</button> </div> <script src="js/vue.js"></script> <script> const app = new Vue({ el:"#app", methods:{ showChildren(){ console.log(this.$children); } }, components:{ 'v-cpn':{ template:"#cpn", methods:{ show(){ console.log("cpn子标签 - show方法"); } } } } }) </script>
点击后:
他是有很多很多个,数组来的,因为他可以有很多个 子组件
你要获取可以这样: this.$children[x] x代表下标,当然 从0 开始。
一看到是下标 你立马要想到什么? 想到 循环遍历对吧 啊哈哈。
里面包含了 子组件的所有,最典型的就是data 和 method 了 或 其他,下面演示:
<body> <template id="cpn"> <div>不断奋起,直到羔羊变雄狮。</div> </template> <div id="app"> <v-cpn></v-cpn> <!-- 这里加Button 然后点击事件父组件中打印 this.$children --> <button @click="cpn_data_s1">点击查看子组件v-cpn的 data-s1</button> <button @click="cpn_method_show">点击触发子组件v-cpn的 show方法</button> </div> <script src="js/vue.js"></script> <script> const app = new Vue({ el:"#app", methods:{ cpn_data_s1(){ console.log(this.$children[0].s1); //你看 贼方便 }, cpn_method_show(){ this.$children[0].show(); //你看 贼方便 } }, components:{ 'v-cpn':{ template:"#cpn", data(){ return{s1:"举杯祝福后都走散"} }, methods:{ show(){ console.log("cpn子标签 - show方法"); } } } } }) </script>