组合式API下的父传子
在 Vue 3 的组合式 API 中,父组件向子组件传递数据可以通过以下几种方式实现:
- Props:可以在父组件中给 子组件绑定属性。在子组件中,可以通过
props
选项接收父组件传递的数据。
基本思想:
- 父组件中给子组件绑定属性
- 子组件内部通过props选项接收
示例代码如下:
// 父组件
<script setup>
import { ref } from 'vue'
import SonCom from './son-com.vue'
const count = ref(100)
setTimeout(() => {
count.value = 200
}, 3000)
</script>
<template>
<div class="father">
<h2>father component</h2>
// 1.绑定属性
<SonCom :count="count" message="father message" />
</div>
</template>
<style scoped>
</style>
// 子组件
<script setup>
// 2. defineProps 接收数据
const props = defineProps({
message: String,
count: Number
})
</script>
<template>
<div class="son">
<h3>son component</h3>
<div>
父组件传入的数据-{{ mmessage }}-{{ count }}
</div>
</div>
</template>
<style scoped>
</style>
-
Provide/Inject:使用
provide
和inject
可以在父组件中提供数据,并在子组件中注入并使用。这种方式允许跨越多个层级进行数据传递。示例代码如下:// 组件嵌套关系:RoomPage -> RoomMsgItem -> RoomMsgComment // 顶层组件 room-page <script setup> import { provide, ref } from 'vue' import RoomMsgIten from './room-msg-item.vue' // 1. 顶层组件提供数据 provide('data-key', 'this is room data') // 传递响应式数据 const count = ref(0) provide('count-key', count) setTimeout(() => { count.value = 100 }, 3000) // 传递方法 const setCount = () => { count.value++ } provide('setCount-key', setCount) </script> <template> <div class="page"> 顶层组件 <RoomMsgItem /> </div> </template> <style scoped> </style> // 底层组件 room-msg-comment <script setup> import { inject } from 'vue' // 2. 接收数据 const roomeData = inject('data-key') // 接收响应式数据 const countData = inject('count-key') // 接收方法 const setCount = inject('setCount-key') </script> <template> <div class="comment"> 底层组件 <div> 来自顶层组件中的数据: {{roomData}} </div> <div> 来自顶层组件中的响应式数据: {{countData}} </div> <div> <button @click="setCount">修改顶层组件的数据count </button> </div> </div> </template> <style scoped> </style>
在上述示例中,父组件使用 provide
函数提供名为 'message'
的数据。在子组件中使用 inject
函数接收 'message'
数据,并在模板中使用。
通过以上两种方式,父组件可以将数据传递给子组件,并在子组件中使用。可以根据具体的场景和需求选择适合的方式进行数据传递。
组合式API下的子传父
在 Vue 3 的组合式 API 中,子组件向父组件传递数据可以通过以下几种方式实现:
- 自定义事件:子组件可以使用 emit方法触发事件,并将数据作为参数传递给父组件。父组件可以在模板中使用
@
或v-on
语法监听子组件的自定义事件,并在触发事件时执行相应的方法。
基本思想:
- 父组件中给子组件标签通过@绑定事件
- 子组件内部通过emit方法触发事件
示例代码如下:
// 父组件
<script setup>
import SonCom from './son-com.vue'
const getMessage = (msg) => {
console.log(msg)
}
</script>
<template>
<div class="father">
<h2>father component</h2>
// 1.绑定事件
<SonCom @get-message="getMessage" />
</div>
</template>
<style scoped>
</style>
// 子组件
<script setup>
// 2. 通过 defineEmits() -> emit(this.$emit)
const emimt = defineEmits(['get-message'])
const sendMsg = () => {
emit('get-message', 'this is son message')
}
</script>
<template>
<div class="son">
<h3>son component</h3>
<button @click="sendMsg">触发自定义事件</button>
</div>
</template>
<style scoped>
</style>
provide
/inject
:在组合式 API 中,子组件可以使用provide
函数向上层组件提供数据,然后父组件通过inject
函数接收子组件提供的数据。这种方式适用于跨越多个层级的数据传递。原理和上述父传子第二种方法相同。
通过以上两种方式,子组件可以向父组件传递数据。