13.v3+ts的父子组件传值

1.0父传子
1.1父组件传值
<template>
  <div class="container">
    <Head title="我不知道怎么说" :arr="[1,2,3]"></Head>
    <Foot></Foot>
    <Content></Content>
  </div>
</template>

<script setup lang='ts'>
import { reactive, ref } from 'vue'
import Head from './components/head.vue'
import Foot from './components/footer.vue'
import Content from './components/content.vue'
1.2子组件接收
<template>
  <div class="container">
    头部:{{ title }}
    <ul>
      <li v-for="item in arr">2</li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
// 不需要默认值的时候
// const props = defineProps<{
//   title: string;
//   arr: number[];
// }>();
// console.log(props.title);
// console.log(props.arr);

type arrs = number | string

// 需要默认值
withDefaults(
  defineProps<{
    title: string;
    arr: arrs[];
  }>(),
  {
    // 当父组件没有传递的时候,默认展示[2,2]
    arr:()=>['2',2]
  }
);


</script>
2.0子传父
2.1子组件
<template>
  <div class="container">
    <h1>子组件</h1>
    <button @click="send">给父组件传值</button>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
// 数组里面的名字可以自定义 与父组件绑定的一致就行
//非ts写法
const emit = defineEmits(["on-click"]);

//ts写法
interface My {
  name:string
  age:number
}
const emit = defineEmits<{
  (e:'on-click',my:My):void
  //传递多个就多写
  //(e:'on-click',my:My):void
}>()


const send = () => {
  let my = { 
    name: "何",
    age: 20,
  };
  emit("on-click", my);
};
</script>
2.2父接收
<template>
  <div class="container">
    <Head @on-click="getMy"></Head>
  </div>
</template>

<script setup lang='ts'>
import { reactive, ref } from 'vue'
import Head from './components/head.vue'
interface My {
  name:string
  age:number
}
const getMy = (myInfo:My) => {
  console.log(myInfo);
}
</script>
3.0 通过defineExpose子组件暴露自身方法和数据
3.1子组件
<template>
  <div class="container">
    <h1>子组件</h1>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";

defineExpose({
  name:'何',
  open:() => console.log(222)
})
</script>
3.2父组件接收
<template>
  <div class="container">
    <!-- 给组件绑定ref -->
    <Head ref="theName"></Head>
    <button @click="receive">get</button>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import Head from "./components/head.vue";
//InstanceType<typeof Head> 是拿到子组件暴露出来的类型
const theName = ref<InstanceType<typeof Head>>();

const receive = () => {
  console.log(theName.value?.name);
  theName.value?.open()
};
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值