$root
当前组件树的根组件实例。如果当前实例没有父组件,那么这个值就是它自己。
完整案例:05_component/18_root.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>父子组件</title> </head> <body> <div id="app"> <my-parent></my-parent> </div> </body> <template id="parent"> <div> <h1>父组件 - {{ $root.msg }}</h1> <my-child></my-child> </div> </template> <template id="child"> <div> <h3>子组件 - {{ $root.msg }}</h3> <button @click="$root.fn()">按钮</button> </div> </template> <script src="../lib/vue.global.js"></script> <script> const Child = { template: '#child' } const Parent = { template: '#parent', components: { 'my-child': Child } } Vue.createApp({ data () { return { msg: 'root' } }, methods: { fn () { console.log('root 被调用') } }, components: { 'my-parent': Parent } }).mount('#app') </script> </html>