VUE父子组件传值

这篇博客介绍了Vue中父子组件间的通信方式,包括通过props从父组件向子组件传递数据,以及使用this.$emit触发自定义事件将数据回传给父组件。同时,展示了如何利用$ref属性在父组件中直接引用子组件的方法和数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、props / $emit

        父传子,子组件用props接收

        子传父,this.$emit

1、子组件代码

<template>
    <div class="car">
        <p>我是登录页的购物车组件</p>
        <p>父组件传递过来的数据:{{ names }}</p>
        <button @click="servew">点击我</button>
    </div>
</template>
<script>
export default {
    // -----------------
    props: {
        names: {
            type: String,
            default: "",
        },
    },
    // -----------------
    data() {
        return {
            msg: "我是msg",
            msgs: "我是msgs",
        };
    },
    methods: {
        servew() {
            this.$emit("hahahas", this.msgs);
        },
    },
};
</script>
<style  scoped>
.car {
    width: 100%;
    height: 400px;
    background-color: pink;
}
</style>

2、父组件代码

<template>
    <div class="box">
        <div @click="home">我是登录页</div>
        {{ name }}
        <car :names="name" @hahahas="hahaha" ref="childselected"></car>
        <p>子组件传递给父组件的数据:{{ number }}</p>
    </div>
</template>
<script>
import car from "@/components/car.vue";
export default {
    components: {
        car,
    },
    data() {
        return {
            name: "小米",
            number: "",
        };
    },
    mounted() {
        this.number = this.$refs.childselected.msg;
    },
    methods: {
        home() {
            this.$router.push({
                path: "/home",
            });
        },
        hahaha(e) {
            console.log(e);
            this.number = e;
        },
    },
};
</script>
<style  scoped>
.box {
    width: 100%;
    height: 100%;
}
</style>

二、$ref可以让父组件更加便利地取到想要的子组件

1、子组件定义数据后无需任何操作

 

 2、父组件中定义ref 并取值

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值