<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <script src="../js/vue.js"></script> <div id="app"> <!--使用但标签的方式是不可以的--> <cpn></cpn> <button @click="btnclick">按钮</button> </div> <template id="cpn"> <div>我是子组件</div> </template> <script> let app=new Vue({ el:'#app', data:{ message:'hello world' }, methods:{ btnclick(){ console.log(this.$children); // this.$children[0].showMessage(); for(let c of this.$children){ console.log(c.name); c.showMessage(); } } }, components:{ cpn:{ template:'#cpn', data(){ return{ name:'我是子组件的name' } }, methods:{ showMessage(){ console.log("==========showMessage"); } } } } }) </script> </body> </html>
运行结果: