总结一下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>
  • 效果
相关推荐
用户14567756103712 小时前
文件太大传不了?用它一压,秒变合格尺寸!
前端
用户14567756103712 小时前
再也不用一张张处理了!批量压缩神器来了,快收藏
前端
心.c12 小时前
一套完整的前端“白屏”问题分析与解决方案(性能优化)
前端·javascript·性能优化·html
white-persist13 小时前
【burp手机真机抓包】Burp Suite 在真机(Android and IOS)抓包手机APP + 微信小程序详细教程
android·前端·ios·智能手机·微信小程序·小程序·原型模式
俺会hello我的13 小时前
舒尔特方格开源
前端·javascript·开源
lbh13 小时前
Chrome DevTools 详解(二):Console 面板
前端·javascript·浏览器
ObjectX前端实验室13 小时前
【react18原理探究实践】更新阶段 Render 与 Diff 算法详解
前端·react.js
wxr061613 小时前
部署Spring Boot项目+mysql并允许前端本地访问的步骤
前端·javascript·vue.js·阿里云·vue3·springboot
万邦科技Lafite14 小时前
如何对接API接口?需要用到哪些软件工具?
java·前端·python·api·开放api·电商开放平台
知识分享小能手14 小时前
微信小程序入门学习教程,从入门到精通,WXSS样式处理语法基础(9)
前端·javascript·vscode·学习·微信小程序·小程序·vue