总结一下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>
  • 效果
相关推荐
木子雨廷15 分钟前
Flutter 开发一个plugin
前端·flutter
重生之我是一名前端程序员17 分钟前
websocket + xterm 前端实现网页版终端
前端·websocket
sorryhc19 分钟前
【AI解读源码系列】ant design mobile——Space间距
前端·javascript·react.js
uhakadotcom33 分钟前
NPM与NPX的区别是什么?
前端·面试·github
GAMC43 分钟前
如何修改node_modules的组件不被install替换?可以使用patch-package
前端
页面仔Dony43 分钟前
webpack 与 Vite 深度对比
前端·前端工程化
Juchecar1 小时前
Vue3 组件生命周期详解
前端·vue.js
页面仔Dony1 小时前
打包工具配置base、publicPath字段的作用和区别
前端·前端工程化
gongzemin1 小时前
前端下载xlsx 提示试图打开文件时遇到错误
前端
我是ed1 小时前
# JS获取用户访问网页的浏览器、IP、地址等信息 实现访问统计
前端