总结一下vue3的组件之间数据转递,子组件传父组件,父组件传子组件

文章目录

父传子

1.子组件定义属性

html 复制代码
<!-- 子组件代码 -->
<template> 
<h1>子组件</h1> 
    <div>这是一个子组件</div>
    <div>标题:{{ title }}</div>
    <div>名称:{{ name }}</div>
    <div>年龄:{{ age }}</div>
</template> 
<script lang="ts" setup>
import { defineProps,ref} from 'vue';
//定义属性,
const attribute = defineProps({
    title:{
        // title属性string类型
        type:String,
        required: true//必填
    },
    name:{
        type:String,
        required:true
    },
    age:{
        type:Number,
        required:true
    }
});
const title=ref("");
const name=ref("");
const age=ref(0);
title.value=attribute.title
name.value=attribute.name
age.value=attribute.age
</script>
html 复制代码
<!-- 父组件代码 -->
<template>
    <h1>父组件</h1>
    <hr> 
    <!-- 给组件属性传参 -->
    <son :title="sonTitle" :name="sonName" :age="sonAge"   ></son>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import son from './Son.vue'; 
const sonTitle=ref("子标题");
const sonName = ref("子名称");
const sonAge = ref("子年龄");
</script>
  • 效果:

子传父

  1. 现在子组件定义函数
html 复制代码
<!-- 子组件代码 -->
<template> 
    <h1>子组件</h1> 
        <div>这是一个子组件</div>
        <div>标题:<el-input v-model="title" /></div>
        <div>名称:<el-input v-model="name" /></div>
        <div>年龄:<el-input v-model="age" /></div>
        <button @click="f_SonSendParent">发送给父组件</button>
</template> 
<script lang="ts" setup>
    import { defineEmits,ref} from 'vue';  
    const ParentEvent = defineEmits(["EventName"])//定义组件自己的函数,
    const title=ref("");
    const name=ref("");
    const age=ref(0);
    const f_SonSendParent=()=>{
        ParentEvent("EventName",title.value,name.value,age.value);
    }
</script> 
  1. 父组件给子组件定义的函数传入函数
html 复制代码
<!-- 父组件代码 -->
<template>
    <h1>父组件</h1>
    <hr> 
    接收的参数:<br>
    标题:{{ sonTitle }}<br>
    名称: {{ sonName }}<br>
    年龄:{{ sonAge }}<br>
    <!-- 给组件属性传参 -->
    <son :title="sonTitle" :name="sonName" :age="12"  @EventName="f_a"  ></son>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import son from './Son.vue'; 
const sonTitle=ref("子标题");
const sonName = ref("子名称");
const sonAge = ref(2);
const f_a=(a:string,b:string,c:number)=>{
    sonTitle.value=a;
    sonName.value=b;
    sonAge.value=c;
}
</script>
  • 效果
相关推荐
REDcker12 小时前
显示分辨率标准对照详解
前端·网络·分辨率·显示·屏幕
এ慕ོ冬℘゜12 小时前
前端实战:jQuery 多条件联合搜索(标题模糊查询 + 日历时间段筛选)
前端·javascript·jquery
武子康12 小时前
Search Console Platform Properties 扩大 SEO 资产边界:从 Page Ranking 到 Topic Coverage(5 类误读边界 + 3 表数据层设计)
前端·人工智能·后端
随心点儿12 小时前
js postMessage 实现跨域发送消息-应用示例
javascript·ecmascript·postmessage
一点一木13 小时前
从60首歌到1个网站:输入你的故事,还你一首歌
前端·github
IT_陈寒14 小时前
Vue这个特性差点让我加班到凌晨,谁懂啊
前端·人工智能·后端
kyriewen14 小时前
我让AI改一个bug——它偷偷动了5个我没让它碰的地方
前端·javascript·ai编程
遇乐的果园15 小时前
前端学习笔记-vue加载渲染优化
前端·笔记·学习
用户9850335932815 小时前
OpenLayers 热力图从原理到 Vue 组件一键接入
前端
颜酱15 小时前
01 | 骨架搭建:FastAPI + Vue 跑通第一个 SSE 流式问答
前端·人工智能·后端