vue3学习笔记(4)组件之间的参数传递(带完整代码)

Vue3专栏入口

一、 父传子

父传子十分好理解,需要先创建一个子,一个父如图所示。
在这里插入图片描述

1.1 步骤图解

App.vue中步骤如下:

  1. 导入子组件
  2. 声明子组件
  3. 在Html中使用子组件并添加 :msg=“msg”

这时由steup返回的msg就会被子组件接收

在这里插入图片描述
child.vue中步骤如下

  1. 接收msg
  2. 展示msg
    在这里插入图片描述
    这时就可以正常展示msg了如图
    在这里插入图片描述

1.2 App.vue完整代码:

<template>
  <div>
    <h1>父</h1>
    <h3>{{msg}}</h3>
    <hr>
    <Child :msg="msg"/>
  </div>
</template>

<script>
import { defineComponent, ref } from "vue";
import Child from "./components/child.vue";

export default defineComponent({
  components: {
    Child,
  },

  name: "App",
  
  setup() {
      const msg = ref("小天英俊潇洒")

      return{
          msg,
      }
  },
});
</script>

<style scoped>
</style>

1.3 child.vue完整代码:

<template>
    <div>
        <h1>子</h1>
        <h3>{{msg}}</h3>
    </div>
</template>

<script>

import { defineComponent } from 'vue'
export default defineComponent({
    name:'Child',
    props:["msg"],
    setup(props,context){
        return{
        }
    }
})
</script>

<style scoped>
</style>

二、子传父

2.1 步骤图解

App.vue步骤:

  1. 自定义回调函数
  2. 编写回调函数
  3. 返回回调函数

在这里插入图片描述
child.vue步骤:

  1. 编写按钮分发事件
  2. 编写按钮触发函数,使用emit传递数据
  3. 返回按钮触发函数

在这里插入图片描述
ok子传父搞定
在这里插入图片描述

2.2 App.vue完整代码

<template>
  <div>
    <h1>父</h1>
    <h3>{{ msg }}</h3>
    <hr />
    <Child :msg="msg" @zcf="zcf" />
  </div>
</template>

<script>
import { defineComponent, ref } from "vue";
import Child from "./components/child.vue";

export default defineComponent({
  components: {
    Child,
  },

  name: "App",

  setup() {
    const msg = ref("小天英俊潇洒");

    // 回调函数
    const zcf = (text) => {
      msg.value += text;
    };
    return {
      msg,
      zcf,
    };
  },
});
</script>

<style scoped>
</style>

2.3 child.vue完整代码

<template>
    <div>
        <h1>子</h1>
        <h3>{{msg}}</h3>
        <button @click="emit_zcf">子传父</button>
    </div>
</template>

<script>

import { defineComponent } from 'vue'
export default defineComponent({
    name:'Child',
    props:["msg"],
    setup(props,context){
        // 按钮触发函数
        const emit_zcf = () => {
            context.emit('zcf','子传父')
        }
        return{
            emit_zcf
        }
    }
})
</script>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值