【vue3学习—day4】vue3之父子组件传值问题

父组件传值给子组件

父组件:

<template>
    <div>
        <defu :msg="msg"></defu>
    </div>
</template>
<script setup>
// 引入子组件
import defu from '../components/defu.vue';
let msg = ref("这是父组件里面的参数")

</script>

子组件:

<template>
    <div>
        子组件: {{ msg }}
    </div>
</template>
 
<script setup>
// 接受父组件传过来的参数
defineProps({
    msg: {
        type: String,
        default: "00000"
    }
})
</script>

在这里插入图片描述

子传父

自组件:

<template>
    <div>
        子组件: {{ msg }}
        <div @click="getMsg">你好</div>
    </div>
</template>
 
<script setup lang="ts">
import { ref } from "vue";

// 子传父
let msg = ref("子传父的内容。!@#$")

const emit = defineEmits<{
    (e: "fn", id: String): void
}>()

const getMsg = () => {
    emit("fn", msg)
}

</script>

父组件:

<template>
    <div>
        <defu @fn="getData"></defu>
    </div>
</template>
<script setup>
// 子传父
import defu from '../components/defu.vue';
const getData = (n) => {
    console.log(n.value)
}

</script>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue 3中,父子组件之间传值可以通过props和emit来实现。下面是一种常见的父子组件传值方式: 1. 父组件通过props向子组件传递数据: 在父组件中,可以通过在子组件标签上绑定属性的方式将数据传递给子组件。例如: ```html <template> <div> <child-component :message="parentMessage"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { parentMessage: 'Hello from parent component' }; } }; </script> ``` 在子组件中,可以通过props接收父组件传递的数据。例如: ```html <template> <div> <p>{{ message }}</p> </div> </template> <script> export default { props: { message: { type: String, required: true } } }; </script> ``` 这样,父组件中的`parentMessage`会传递给子组件的`message`属性。 2. 子组件通过emit向父组件传递数据: 在子组件中,可以通过`$emit`方法触发一个自定义事件,并将需要传递给父组件的数据作为参数传递。例如: ```html <template> <div> <button @click="sendMessage">Send Message to Parent</button> </div> </template> <script> export default { methods: { sendMessage() { this.$emit('message-to-parent', 'Hello from child component'); } } }; </script> ``` 在父组件中,可以通过在子组件标签上监听自定义事件的方式接收子组件传递的数据。例如: ```html <template> <div> <child-component @message-to-parent="handleMessageFromChild"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, methods: { handleMessageFromChild(message) { console.log(message); // 输出:Hello from child component } } }; </script> ``` 这样,子组件中通过`$emit`方法触发的`message-to-parent`事件会被父组件中的`handleMessageFromChild`方法捕获,并将子组件传递的数据作为参数传递给该方法。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值