1.父子組件之間的傳值:props
//父組件
<template>
<Message :msg="msg" />
</template>
<script setup>
import Message from "./Message.vue"
const msg= ref('給子組件的信息');
//const msg = reactive(["給子組件的信息"])
</script>
//Message子組件
<template>
<div></div>
</template>
<script setup>
//獲取值 需要通過defineProps暴露出來
const props = defineProps({
msg: String,
//msg:{
//type:String,
//default:''
//}
});
console.log(props)
</script>
2.子組件向父組件傳值emit
//父組件
<template>
<Message @getMsg="getmsg" />
</template>
<script setup>
import Message from "./Message.vue"
const getmsg = (msg)=>{
console.log(msg)
}
</script>
//Message子組件
<template>
<div @click="postMsg">向父組件傳值</div>
</template>
<script setup>
const emit= defineEmits(["getMsg"])
const postMsg=()=>{
emit('getMsg','向父組件傳值')
}
</script>
3.父組件獲取子組件的屬性或者調(diào)用子組件方法ref
//父組件
<template>
<Message ref="message" />
</template>
<script setup>
import Message from "./Message.vue"
const message= ref(null)
onMounted(() => {
console.log(message.value.msg)
message.value.showMsg()
});
</script>
//Message子組件
<template>
<div></div>
</template>
<script setup>
defineExpose({
msg:''子組件屬性值'',
showMsg(){
console.log('子組件方法')
}
});
</script>
4.provide/inject 啟用依賴注入 實(shí)現(xiàn)跨級(jí)訪問祖先組件的數(shù)據(jù)
//父組件
<template>
<Message />
</template>
<script setup>
import Message from "./Message.vue"
import { provide } from "vue"
provide("msg", "父組件信息")
</script>
//Message子組件
<template>
<div></div>
</template>
<script setup>
import { inject } from 'vue';
let msg= ref()
msg= inject('msg') //接收參數(shù)
console.log(msg)
</script>