父组件:
<script setup>
import { ref } from 'vue'
import SonCom from '@/components/Son-com.vue'
const message = ref('parent')
</script>
<template>
<div></div>
<SonCom car="沃尔沃" :message="message"></SonCom>
</template>
<style>
</style>
子组件接收:
<script setup>
// 子组件
const props = defineProps({
car: String,
message: String
})
</script>
<template>
<div class="son">我是子组件</div>
<div>{{ car }}</div>
<div>{{ message }}</div>
</template>
<style scoped>
.son{
width: 100px;
height: 200px;
background-color: #a72b2b;
}
</style>
解释:
子组件:
<script setup>
// 子组件
const props = defineProps({
car: String,
message: String
})
// 子传父
const emit = defineEmits(['updateMessage'])
const updateMsg = () =>{
emit('updateMessage', props.message + 'is update')
}
</script>
<template>
<div class="son">我是子组件</div>
<div>{{ car }}</div>
<div>{{ message }}</div>
<button @click="updateMsg">修改message</button>
</template>
<style scoped>
.son{
width: 100px;
height: 200px;
background-color: #a72b2b;
}
</style>
父组件:
<script setup>
import { ref } from 'vue'
import SonCom from '@/components/Son-com.vue'
const message = ref('parent')
// 修改消息
const updateMessage = (msg) => { message.value = msg}
</script>
<template>
<div>我是父组件</div>
<SonCom car="沃尔沃" :message="message" @updateMessage="updateMessage"></SonCom>
</template>
<style>
</style>
解释:
上层组件(祖组件):
// 跨层传递
// 传递普通类型
provide('upMsg', '上层消息')
// 传递响应式类型
const upObj = ref({ name: 'jingjing'})
provide('upObj', upObj)
// 传递方法:修改响应式类型
const updateObj = (newName) => { upObj.value.name = newName}
provide('updateObj', updateObj)
下层组件(孙组件):
// 接收上层数据
// 接收普通类型
const upMsg = inject('upMsg')
// 接收响应类型
const upObj = inject('upObj')
// 接收方法
const updateObj = inject('updateObj')
案例: