Vue组件通信05-父子组件通信(子到父)-$parent

    科技2025-05-14  6

    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> <br> {{msg}} <Child ></Child> </div> </template> <script> import Child from './Child'; export default { components: { Child, }, data() { return { title: "我是父组件传递的title!", msg: "我是父组件的msg" } }, methods: { setMsg(msg) { this.msg=msg; } }, } </script> <style scoped> </style>

    components/Child.vue

    <template> <div> <hr> <span>我是子组件</span> <button @click="handleClick">点我更改父组件的msg</button> </div> </template> <script> export default { methods: { handleClick() { console.log(this.$parent.msg); this.$parent.setMsg("我是使用$parent更改的父级msg") } }, } </script> <style scoped> </style>

    效果截图:

    Processed: 0.009, SQL: 8