vue3 setup語法糖父子組件的通信


在setup語法糖中父子組件的寫法有兩種
1、第一種用defineProps和defineEmits
(1) 父組件傳值給子組件,子組件用defineProps接收
父組件代碼:


<template>
  <div class="home">
    <HelloWorld :msg="num" @change="change" />
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue';
//components
import HelloWorld from '@/components/HelloWorld.vue'; 
//變量
const num=ref<number>(0);
</script>

HelloWorld 子組件代碼:

<template>
  <div class="hello">
    <h1>我是hello頁面</h1>
    <p>{{msg}}</p>
  </div>
</template>

<script lang="ts" setup>
import {defineProps,defineEmits} from 'vue'
const prop=defineProps({
  msg:Number
})
</script>

<style scoped>

</style>

(2) 子組件用 defineEmits 傳遞給父組件信息
HelloWorld子組件

<template>
  <div class="hello">
    <h1>我是hello頁面</h1>
    <p>{{msg}}</p>
    <button @click="add">增加</button>
  </div>
</template>

<script lang="ts" setup>
import {defineProps,defineEmits} from 'vue'
const prop=defineProps({
  msg:Number
})


const emit=defineEmits(['change'])
const add=()=>{
  console.log(prop.msg);
  emit('change','1234')
}
</script>

<style scoped>

</style>


父組件

<template>
  <div class="home">
    <HelloWorld :msg="num" @change="change" />
    <child ref="sonRef"></child>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue';
//components
import HelloWorld from '@/components/HelloWorld.vue'; 
//變量
const num=ref<number>(0);
//方法
const change=(val:any)=>{
  num.value++
}

</script>

2、父組件使用ref獲取子組件的實例,從而獲取子組件的變量和方法。但是要注意子組件無論是方法還是變量都要用defineExpose暴露出去,否則父組件是接收不到的。
子組件:

<template>
  <div class="child1">
      <p>我是child1頁面</p>
  </div>
</template>

<script lang="ts" setup>
import {ref,defineExpose} from 'vue'
//變量
const msg=ref<string>('1245');
//方法
const sonMethod=()=>{
  console.log('我是子頁面的方法');
  
}
defineExpose({
  msg,
  sonMethod
})
</script>

<style scoped>

</style>

父組件:

<template>
  <div class="home">
    <child ref="sonRef"></child>
    <button @click="getSon">父組件獲取子組件的實例</button>
  </div>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue';
//components
import child from '../components/ChildOne.vue'
//子組件的類型
const sonRef=ref<InstanceType<typeof child>>();

const getSon=()=>{
  console.log(sonRef.value?.msg);
  sonRef.value?.sonMethod();
  
}
</script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM