vue3組件之間傳值

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>
 //獲取值  需要通過(guò)defineProps暴露出來(lái)
 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>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容