VUE3父子组件传值 小范例代码

[复制链接]
查看: 201   回复: 0

164

主题

164

帖子

939

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
939
2023-5-27 15:44:31   显示全部楼层   阅读模式  
1.jpg



1.在Vue3中,子组件可以通过props接收父组件传递的值,也可以通过$emit方法向父组件发送事件。具体操作如下:

父组件传递值给子组件:
父组件中使用子组件时,可以在子组件标签上使用属性绑定的方式,将父组件中的数据传递给子组件:


  1. <template>
  2.   <div>
  3.     <ChildComponent :msg="parentMsg" />
  4.   </div>
  5. </template>

  6. <script>
  7. import ChildComponent from './ChildComponent.vue'

  8. export default {
  9.   name: 'ParentComponent',
  10.   components: { ChildComponent },
  11.   data() {
  12.     return {
  13.       parentMsg: 'Hello from parent!'
  14.     }
  15.   }
  16. }
  17. </script>
复制代码


子组件中通过props接收父组件传递的值:

  1. <template>
  2.   <div>
  3.     {{ msg }}
  4.   </div>
  5. </template>

  6. <script>
  7. export default {
  8.   name: 'ChildComponent',
  9.   props: {
  10.     msg: String
  11.   }
  12. }
  13. </script>
复制代码

2.子组件向父组件发送事件:
子组件中通过$emit方法触发一个自定义事件,父组件通过在子组件标签上使用v-on绑定自定义事件的方式,监听子组件触发的事件并处理:

  1. <template>
  2.   <div>
  3.     <button @click="sendMsg">发送消息到父组件</button>
  4.   </div>
  5. </template>

  6. <script>
  7. export default {
  8.   name: 'ChildComponent',
  9.   methods: {
  10.     sendMsg() {
  11.       this.$emit('send-msg', 'Hello from child!')
  12.     }
  13.   }
  14. }
  15. </script>
复制代码

父组件中监听子组件触发的事件,并处理:

  1. <template>
  2.   <div>
  3.     <ChildComponent @send-msg="handleMsg" />
  4.   </div>
  5. </template>

  6. <script>
  7. import ChildComponent from './ChildComponent.vue'

  8. export default {
  9.   name: 'ParentComponent',
  10.   components: { ChildComponent },
  11.   methods: {
  12.     handleMsg(msg) {
  13.       console.log(msg)
  14.     }
  15.   }
  16. }
  17. </script>
复制代码


回复

使用道具 举报

您需要登录后才可以回帖   登录 立即注册

高级模式

南通谢凡软件科技有限公司