本文只给干货:Vue2 和 Vue3 中父子通信的常用写法,每个示例都是可直接运行的 .vue 文件。适合快速查阅和复制。

一、Vue2 父子通信

1. 父传子:props

Parent.vue

<template>
  <div>
    <Child :msg="message" :user="userInfo" />
  </div>
</template>

<script>
import Child from './Child.vue'

export default {
  components: { Child },
  data() {
    return {
      message: 'Hello from parent',
      userInfo: { name: 'Tom', age: 20 }
    }
  }
}
</script>

Child.vue

<template>
  <div>
    <p>{{ msg }}</p>
    <p>{{ user.name }} - {{ user.age }}</p>
  </div>
</template>

<script>
export default {
  props: {
    msg: String,
    user: Object
  }
}
</script>

2. 子传父:$emit

Parent.vue

<template>
  <div>
    <Child @send-data="handleData" />
    <p>收到子组件数据:{{ received }}</p>
  </div>
</template>

<script>
import Child from './Child.vue'

export default {
  components: { Child },
  data() {
    return { received: '' }
  },
  methods: {
    handleData(val) {
      this.received = val
    }
  }
}
</script>

Child.vue

<template>
  <button @click="sendToParent">点击发送数据</button>
</template>

<script>
export default {
  methods: {
    sendToParent() {
      this.$emit('send-data', 'Hello from child')
    }
  }
}
</script>

二、Vue3 父子通信(Composition API with <script setup>

1. 父传子:defineProps

Parent.vue

<template>
  <div>
    <Child :msg="message" :user="userInfo" />
  </div>
</template>

<script setup>
import Child from './Child.vue'
import { ref } from 'vue'

const message = ref('Hello from parent')
const userInfo = ref({ name: 'Tom', age: 20 })
</script>

Child.vue

<template>
  <div>
    <p>{{ msg }}</p>
    <p>{{ user.name }} - {{ user.age }}</p>
  </div>
</template>

<script setup>
defineProps({
  msg: String,
  user: Object
})
// 或用 TypeScript: defineProps<{ msg: string; user: { name: string; age: number } }>()
</script>

2. 子传父:defineEmits

Parent.vue

<template>
  <div>
    <Child @send-data="handleData" />
    <p>收到子组件数据:{{ received }}</p>
  </div>
</template>

<script setup>
import Child from './Child.vue'
import { ref } from 'vue'

const received = ref('')
const handleData = (val) => {
  received.value = val
}
</script>

Child.vue

<template>
  <button @click="sendToParent">点击发送数据</button>
</template>

<script setup>
const emit = defineEmits(['send-data'])

const sendToParent = () => {
  emit('send-data', 'Hello from child')
}
</script>

三、快速对比表

场景 Vue2 写法 Vue3 写法
父传子 props: ['xxx'] defineProps(['xxx'])
子传父 this.$emit('event', val) const emit = defineEmits(['event']); emit('event', val)

更多推荐