Vue3 TS寫法 父子組件傳值(通訊)

父組件向子組件傳值

父組件: (注意,這裏msg綁定的是一個常亮字符串;如果綁定的是一個變量,那麼要這麼寫 :msg="msgVal")

//ParentView.vue
<template>
  <div>
    父親頁面
    <br>
    兒子傳給父親的數據:{{ Fval }}
    <Children msg="你好啊!" />
  </div>
</template>
 
<script setup lang="ts">
import Children from "./ChildrenView.vue";
</script>

子組件:

通過defineProps來接受數據(無須引入直接使用即可)

子組件可寫默認值也可以不寫兩種情況

//ChildrenView.vue
 
<template>
  <h1>兒子接收到的數據:{{ msg }}</h1>
</template>
 
<script lang="ts" setup>
//TODO:接受父親傳遞的數據 無默認值
// const props = defineProps<{msg: string}>()
 
//TODO:接受父親傳遞的數據 但父親沒有傳數據 有默認值
//方法一:
 js寫法
// const props = defineProps({
//   msg: {
//     type:String,
//     default:'默認值11'
//   },
// })
//方法二:
const props = withDefaults(defineProps<{
  msg?: string
}>(), {
  msg: '默認值你好啊!'
})
</script>

子組件向父組件傳值

子組件通過defineEmits派發一個事件 (一樣無須引入直接使用即可)

<template>
  <button @click="reqclick">傳給父親數據</button>
</template>
 
<script lang="ts" setup>
//TODO:給父親傳數據
const emit = defineEmits<{
  (event: 'chilFun', val: number): void
}>()
//const emit = defineEmits(['chilFun']) // 自定義chilFun事件
const reqclick = ()=>{
  emit('chilFun',1212) //1212:傳個父組件的數據
}
</script>

 父組件接受子組件的事件 chilFun

<template>
  <div>
    父親頁面
    <br/>
    兒子傳給父親的數據:{{ Fval }}
    <Children @chilFun="csFun" msg="你好啊!" />
  </div>
</template>
 
<script setup lang="ts">
import { ref } from 'vue'
import Children from './ChildrenView.vue';
const Fval = ref<number>();
//獲得子組件傳過來的數據
const csFun = (val:number) => {
 Fval.value = val;
}
</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章