Vue3+TypeScript父子组件传值

有时候,不是因为你没有能力,也不是因为你缺少勇气,只是因为你付出的努力还太少,所以,成功便不会走向你。而你所需要做的,就是坚定你的梦想,你的目标,你的未来,然后以不达目的誓不罢休的那股劲,去付出你的努力,成功就会慢慢向你靠近。

导读:本篇文章讲解 Vue3+TypeScript父子组件传值,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

将数据从父组件传递到子组件(Props)

子组件

我们先来创建一个子组件

<template>
  <div class="child">
    <h3>{{title}}</h3>
    <p>{{content}}</p>
  </div>
</template>
<script setup lang="ts">
  //从父级接收数据,定义接口
  interface Props {
    title: string;
    content: string
  }

  //defineProps() 加上定义的接口名称
 // defineProps<Props>();
const propsData = defineProps<Props>();
  console.log('propsData',propsData.title,propsData.content)
</script>

以上代码,我们从父级接收到数据,并定义了数据接口,然后使用defineProps() 加上定义的接口名称。也可以定义一个propsData参数来打印出数据。

父组件

<template>
  <child-comp title="学习vue3" :content="content" />
</template>

<script setup>
import ChildComp from "../../components/ChildComp.vue";
import {ref} from "vue";
const content = ref('一起来学习vue3吧')
</script>

将数据从子组件传递到父组件(Emit)

子组件

<template>
  <div class="child">
    <h3>{{title}}</h3>
    <p>{{content}}</p>
    <button @click="buttonClick">点击获取数据</button>
  </div>
</template>
<script setup lang="ts">
  //从父级接收数据,定义接口
  interface Props {
    title: string;
    content: string
  }

  //defineProps() 加上定义的接口名称
  const propsData = defineProps<Props>();
  console.log('propsData',propsData.title,propsData.content)

  //给传给父组件的数据定义一个接口
  interface Emits {
    (event:"sendMessage",msg:msg) : void;
  }
  const emit = defineEmits<Emits>();

  //定义一个msg的数据
  const msg = '这是从子组件传到父组件的数据'
  const buttonClick = () => {
    emit("sendMessage",msg)
  }
</script>

父组件

<template>
  <child-comp title="学习vue3" :content="content"  @sendMessage="getMessage"/>
</template>

<script setup>
import ChildComp from "../../components/ChildComp.vue";
import {ref} from "vue";
const content = ref('一起来学习vue3吧')

//在父组件接收子组件传过来的数据
const getMessage = (msg) => {
  console.log('msg',msg)
}
</script>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/144768.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!