vue-cli子组件传值给父组件

在vue-cli中如何实现子组件传值给父组件

下面通过一个小例子给大家演示一下
一、创建一个vue-cli项目
在这里插入图片描述
二、新建一个子组件son和一个父组件father
在这里插入图片描述
子组件son的代码如下:

<template>
    <div class="son-container">
        <h1>我是儿子</h1>
    </div>
</template>
<script>
export default{
    data(){
        return{
            send_value:"给爸爸的礼物"
        }
    },
    created(){
        this.$emit("give_father",this.send_value)
    }
}
</script>

<style scoped>
.son-container{
    width: 200px;
    height: 200px;
    background-color: red;
}
</style>

父组件的代码如下:

<template>
    <div class="father-container">
        <h1>我是爸爸</h1>
        <son @give_father="get"></son>
        <h3>{{from_son}}</h3>
    </div>
</template>
<script>
import son from "@/components/son";
export default{
    components:{
        son
    },
    data(){
        return{
            from_son:""
        }
    },
    methods:{
        get(data){
            console.log(data);
            this.from_son = data
        }
    }
}
</script>
<style scoped>
.father-container{
    width: 400px;
    height: 400px;
    background-color: green;
}
</style>

传递过程如下:
在这里插入图片描述
最后实现的效果:
在这里插入图片描述
好啦,本期知识点就到这里了,有疑问的小伙伴请在下方留言哦

在Vue3中,组件向父组件传递值可以通过自定义事件和props属性来实现。 1. 使用自定义事件: 组件可以通过`$emit`方法触发一个自定义事件,并将需要传递的值作为参数传递给父组件。在父组件中,可以通过在组件上监听该自定义事件来接收传递的值。 组件代码示例: ```vue <template> <button @click="sendValue">传递值给父组件</button> </template> <script> export default { methods: { sendValue() { this.$emit('custom-event', '传递的值'); } } } </script> ``` 父组件代码示例: ```vue <template> <div> <child-component @custom-event="handleValue"></child-component> <p>接收到的值:{{ receivedValue }}</p> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { receivedValue: '' } }, methods: { handleValue(value) { this.receivedValue = value; } } } </script> ``` 2. 使用props属性: 父组件可以通过props属性向组件传递一个变量,组件可以通过props接收该变量,并在需要时修改它。父组件可以监听组件的变化来获取传递的值。 父组件代码示例: ```vue <template> <div> <child-component :value="receivedValue" @update-value="handleValue"></child-component> <p>接收到的值:{{ receivedValue }}</p> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { receivedValue: '' } }, methods: { handleValue(value) { this.receivedValue = value; } } } </script> ``` 组件代码示例: ```vue <template> <div> <button @click="updateValue">修改值并传递给父组件</button> </div> </template> <script> export default { props: ['value'], methods: { updateValue() { const newValue = '新的值'; this.$emit('update-value', newValue); } } } </script> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值