Vue Component 子访问父组件 $parent
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <div_box ref="box"></div_box> </div> <template id="div_box"> <div style="background-color: red;height: 200px;height: 200px;"> <button-counter></button-counter> </div> </template> <template id="button_counter"> <button @click="btnClick">btn_{{count}}</button> </template> <script src="js/vue.3.2.2.js"></script> <script> const Counter = { data(){ return{ count: 0 } }, template:'#button_counter', methods:{ btnClick() { this.count++; console.log("btnClick--$parent--"+this.$parent.msg); console.log("btnClick--$parent.$parent--"+this.$parent.$parent.msg); console.log("btnClick--$root--"+this.$root.msg); } } } const Box = { data(){ return{ msg:"hello" } }, components: { 'button-counter':Counter }, template:'#div_box' } // 1、创建Vue的实例对象 const app = Vue.createApp({ data(){//定义数据 return { msg:'你好!' } }, components:{ 'div_box':Box//, // 'div_box2':Box2, // 'div_box3':Box3 }, methods: { } }).mount('#app'); </script> </body> </html>