Vue组件通信02-父子组件通信(父到子)-$children

    科技2025-05-05  11

    App.vue

    <template> <div id="app"> <Parent></Parent> </div> </template> <script> import Parent from './components/Parent' export default { name: 'App', components: { Parent } } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>

    components/Parent.vue

    <template> <div> <span>我是父组件</span> <Child></Child> </div> </template> <script> import Child from './Child'; export default { components: { Child, }, mounted () { console.log(this.$children[0].title); this.$children[0].setTitle(); }, } </script> <style scoped> </style>

    components/Child.vue

    <template> <div> <hr> <span>我是子组件</span> <br> 这里子组件的title:{{title}} </div> </template> <script> export default { data() { return { title: "我是子组件的title!" } }, methods: { setTitle() { this.title="更改后的子组件title!" } }, } </script> <style scoped> </style>

    效果截图:

    Processed: 0.010, SQL: 8