Vue3中组合式ApI的父子组件的数据传递

目录

一、父传子

二、子传父


一、父传子

父组件

<template>
  <div class="fa">
    <h2>父组件</h2>
    <p>a={
   { a }}</p>
    <!-- @change用来接收子传父,然后通过事件 -->
    <Son :a="a"></Son>
    <button @click="add">+</button>
  </div>
</template>

<script setup>
 import Son from './Son.vue';
import { ref } from 'vue';
 const a=ref(100)

 const add=()=>{
    a.value++
 }

</script>

<style>
.fa{
    border:1px solid black;
    height: 300px;
    width: 300px;
}
</style>

子组件:

<template>
  <div class="son">
    <h3>子组件</h3>
    <p>a={
   { a }}</p>
  </div>
</template>

<script setup>

const props=defineProps({
    a:Number
})

</script>

<style>
.son{
    border: 1px solid red;
    width: 200px;
    height: 200px;
}
</style>

二、子传父

父组件:

<template>
  <div class="fa">
    <h2>父组件</h2>
    <p>a={
   { a }}</p>
    <!-- @change用来接收子传父,然后通过事件 -->
    <Son :a="a" @changea="changeFn"></Son>
  </div>
</template>

<script setup>
 import Son from './Son.vue';
import { ref } from 'vue';
 const a=ref(100)

const changeFn=(newvalue)=>{
    a.value-=newvalue
}
</script>

<style>
.fa{
    border:1px solid black;
    height: 300px;
    width: 300px;
}
</style>

子组件:

<template>
  <div class="son">
    <h3>子组件</h3>
    <p>a={
   { a }}</p>
    <button @click="change">修改a的值</button>
  </div>
</template>

<script setup>

const props=defineProps({
    a:Number
})

const emit=defineEmits(['changea'])

const change=()=>{
    // 第一个参数与上面宏定义的名字一致,第二个就是传递的参数
    emit('changea',10)
}

</script>

<style>
.son{
    border: 1px solid red;
    width: 200px;
    height: 200px;
}
</style>

相关推荐

  1. Vue3组合ApI父子组件数据传递

    2023-12-11 19:22:02       81 阅读
  2. Vue3父子组件传值问题

    2023-12-11 19:22:02       15 阅读
  3. Vue父子组件传递【极简版】

    2023-12-11 19:22:02       39 阅读
  4. Vue3如何实现组件之间数据传递

    2023-12-11 19:22:02       38 阅读
  5. vue3+vite+ts父子组件之间传值

    2023-12-11 19:22:02       45 阅读
  6. vue3父子组件之间传值方式

    2023-12-11 19:22:02       22 阅读
  7. Vue 3 组合 API:优化代码利器

    2023-12-11 19:22:02       15 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-11 19:22:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-11 19:22:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-11 19:22:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-11 19:22:02       20 阅读

热门阅读

  1. Linux watch命令监视命令输出

    2023-12-11 19:22:02       47 阅读
  2. QT实现的自定义进度条编程

    2023-12-11 19:22:02       53 阅读
  3. openssl编译和集成

    2023-12-11 19:22:02       76 阅读
  4. python一点通:参数列表里面有星号 * 什么意思?

    2023-12-11 19:22:02       92 阅读
  5. 力扣labuladong一刷day34天

    2023-12-11 19:22:02       40 阅读
  6. ubuntu apt指令集学习心得

    2023-12-11 19:22:02       31 阅读
  7. 动态规划算法介绍

    2023-12-11 19:22:02       68 阅读
  8. Oracle中decode函数使用

    2023-12-11 19:22:02       33 阅读
  9. MySQL面试

    2023-12-11 19:22:02       38 阅读
  10. 【redis笔记】分布式锁

    2023-12-11 19:22:02       39 阅读