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>

 

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