首页

最近使用

0
暂无使用记录,点击左侧工具开始使用

vue3父子组件相互传值开发说明

父子组件传值是高频操作,核心原则是单向数据流:父组件通过props把数据传给子组件,子组件通过emits把事件或数据传给父组件。

父传子说明

父组件中调用子组件如 <template><Child :msg="message" :user="userInfo" count="123" /></template>,其中msg、user为子组件接收的变量名,为动态绑定;count为静态值,message,userInfo为父组件的值,其中 : 是动态绑定,传递变量;没有 : 是静态字符串

子组件通过 const props = defineProps(['msg', 'user', 'count']) 来简单接收,vue3是建议用 TypeScript 来设置变量名类型来更加的严谨。需要注意的是:props 是只读的!子组件绝对不能尝试修改 props.msg = '新值',这会破坏数据流并触发警告。如果子组件想修改,正确的做法是触发一个事件,交给父组件去改。

子传父

子组件defineEmits通过触发自定义事件,把数据“抛”给父组件。

子组件(Child.vue)

<script setup>
// 声明事件(推荐数组或对象写法)
const emit = defineEmits(['updateMsg', 'sendData'])

function handleClick() {
  // 触发 updateMsg 事件,并携带参数
  emit('updateMsg', '子组件发来的新消息')
}

function sendComplex() {
  emit('sendData', { id: 1, content: '复杂数据' })
}
</script>

<template>
  <button @click="handleClick">发送消息给父组件</button>
  <button @click="sendComplex">发送对象</button>
</template>
父组件(Father.vue)

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

const parentMsg = ref('初始内容')

// 接收事件,参数就是子组件 emit 时带过来的
function onUpdateMsg(newValue) {
  parentMsg.value = newValue // 在这里真正更新数据
}

function onSendData(data) {
  console.log(data) // { id: 1, content: '复杂数据' }
}
</script>

<template>
  <Child 
    @update-msg="onUpdateMsg" 
    @send-data="onSendData" 
  />
  <p>父组件收到:{{ parentMsg }}</p>
</template>
说明:父组件中通过 @ 绑定子组件定义的事件名,事件名在模板中要写成 kebab-case (短横线) 形式,如 @update-msg。事件方法为父组件定义的,来接收子组件传来的数据。逻辑是子组件点击定义一个方法,里面操作数据,然后用 emit(父组件绑定的事件名,子组件的数据) 来把数据传到父组件,父组件绑定事件名中的方法接收数据。