vue3 父子组件传值

浅谈Vue3——父子组件传值

前端使用到vue3 + typeScript,最近使用到vue3 的父子组件之间的传值,顺便学习一下,在此总结一下,若有不足之处,望大佬们可以指出。
vue3官网: https://cn.vuejs.org/ link

引言

Vue.js是一款流行的JavaScript框架,用于构建用户界面。它提供了一种简洁、灵活的方式来管理和渲染数据。在Vue3中,父子组件之间的数据传递是一个常见的需求。本文将介绍如何在Vue3中传递对象,并且在子组件中访问和修改父组件对象中的属性值。

父子组件传值的作用

在 Vue 3 中,父子组件之间传值有以下作用:

  1. 组件通信:父组件可以通过向子组件传递数据来实现与子组件的通信。这样,父组件就能将数据传递给子组件,并且子组件可以根据接收到的数据进行渲染或执行相应的操作。

  2. 数据共享:通过父子组件传值,可以在多个组件之间共享数据。当多个子组件需要访问同一个数据时,可以将数据定义在父组件中,然后通过 props 将数据传递给子组件,从而实现数据共享。

  3. 动态配置:父组件可以通过向子组件传递不同的参数或配置,来动态控制子组件的行为。例如,父组件可以根据用户的操作或业务需求,向子组件传递不同的 props 值,以便子组件根据不同的配置进行展示或处理。

  4. 构建组件库:通过父子组件传值,可以构建可复用的组件库。父组件可以定义一些可配置的选项或属性,并将它们作为 props 传递给子组件。这样,其他开发者在使用该组件库时,可以根据自己的需求和场景,通过修改 props 值来自定义组件的行为和外观。

    总之,父子组件之间传值在 Vue 3 中十分重要,它实现了组件之间的通信、数据共享和动态配置等功能,为构建灵活、可复用的组件提供了便利。

一、父向子组件传值

父组件传递参数

<template>
 <!-- 父页面 -->
 <main>
   <el-button type="primary" @click="change">父组件点击</el-button>
   <div class="line"></div>
   <child :msg="msg" />
 </main>
</template>

<script setup lang="ts">
import child from './child.vue';
import { ref } from 'vue';

const msg = ref('父组件msg')

const change = () => {
 msg.value = '父值66666'
}
</script>

<style lang="scss">
.line {
 border: 1px dashed #ccc;
 width: 500px;
 height: 1px;
 margin: 30px 0;
}
</style>

子组件接受参数值

defineEmits: defineEmits() 宏仅限于 setup 语法糖 使用,用来声明组件要触发的事件。

<template>
 <!-- 子组件 -->
 <div class="about">
   <h1>子组件接收父组件值:{{ msg }}</h1>

   <el-button type="primary" @click="childChange">子组件点击</el-button>
 </div>
</template>

<script setup lang="ts">

defineProps({
 msg: {
   type: String,
   default: ''
 }
})
</script>

二、子向父组件传值

子组件传递参数

<template>
  <!-- 子组件 -->
  <div class="about">
    <h1>子组件接收父组件值:{{ msg }}</h1>

    <el-button type="primary" @click="childChange">子组件点击</el-button>
  </div>
</template>

<script setup lang="ts">

defineProps({
  msg: {
    type: String,
    default: ''
  }
})

// 声明组件要触发的事件
const emits = defineEmits(['increase']);

//子组件传值父组件
const childChange = () => {
  //声明不能直接更改父组件传过来的值  msg
  emits('increase', '子组件值8888')
}

</script>

父组件接收参数值

<template>
  <!-- 父页面 -->
  <main>
    <el-button type="primary" @click="change">父组件点击</el-button>
    <div class="line"></div>
    <child :msg="msg" @increase="childHandle" />
  </main>
</template>

<script setup lang="ts">
import child from './child.vue';
import { ref } from 'vue';

const msg = ref('父组件msg')

//父组件点击
const change = () => {
  msg.value = '父值66666'
}

//接收子组件传过来的值
const childHandle = (val: string) => {
  msg.value = val
}

</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值