$parent
当前组件可能存在的父组件实例,如果当前组件是顶层组件,则为 null
。
<!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-root></my-root> </div> </body> <template id="root"> <div style="width: 100%;height: 500px;background-color: #ccc;"> <input type="color" v-model="color"> <my-box></my-box> </div> </template> <template id="box"> <div :style="{ width: '300px', height: '300px', 'background-color': $parent.color }"></div> </template> <script src="../lib/vue.global.js"></script> <script> const Box = { template: '#box' } const Root = { template: '#root', components: { MyBox: Box }, data () { return { color: '#f66' } } } const app = Vue.createApp({ components: { MyRoot: Root } }) app.mount('#app') </script> </html>