Vue中组件之间相互传值(父组件传给子组件,子组件传给父组件)

在Vue项目中,经常会出现,父组件传值给子组件,同时,有时候也希望子组件的值传递给父组件。

场景:比如,你封装了一个input组件,你需要在父组件引用的时候,设置placeholder,这就需要把它传给子组件,同时,你input组件中输入了什么内容,需要给父组件,并在父组件中做逻辑操作。

  • 父组件传值给子组件,这个在传递的过程中依赖于props属性,把要给子组件传递的参数名,配置在props中。

注意点:

1.props是一个数组,也可以是一个{}

//形式一
props:['obj1','obj2','obj3','obj4']
//形式二 支持的类型有 String, Number, Boolean, Function, Object, Array, 
props:{
'obj1':String,
'obj2',[String,Number],
'obj3':{
type:String,
required:true
},
'obj4':{
type:Number,
default:100
}

}

2.变量要用引号包含

  • 使用方法 

在Vue项目中,创建两个模板一个是SuperTemp.vue,另外一个是ChildTemplate.vue,

  • SuperTemp.vue
<template>
    <div class="superTemplate" >
        <p>{{childMsg}}</p>
        <ChildTemplate superMsg='我是父组件内容' v-on:ToSuper='passParam'></ChildTemplate>
    </div>
</template>

<style scoped>
p{
    color:brown;
    font-size: 30px;
}
</style>

<script>
import ChildTemplate from './ChildTemplate';

export default {
    name:'superTemplate',
    components:{
        ChildTemplate:ChildTemplate
    },
    data:function(){
        return {
            childMsg:''
        }
    },
    methods:{
        passParam:function(obj){
            this.childMsg = obj;
        }
    }
}
</script>
  • ChildTemplate.vue
<template>
    <div class="childTemplate">
        <p>{{superMsg}}</p>
        <p>{{childMsg}}</p>
        <button @click="passObj">点击切换</button>
    </div>
</template>

<style scoped>
p{
    color: blue;
    font-size: 40px;
}
button{
    width: 200px;
    height: 50px;
    background: green;
}
</style>

<script>
export default {
    name:'childTemplate',
    props:['superMsg'],
    data:function(){
        return {
            childMsg:'子组件信息'
        }
    },
    methods:{
        passObj:function(){
            this.$emit('ToSuper',this.childMsg);
        }
    }
    
}
</script>

注:1.在子组件给父组件传值时,一般都是借助$emit('监听的时间名','触发的方法名'),而且是在某种条件下响应,比如在某一个点击事件下。

//  ToSuper->监听的事件名  this.childMsg ->传递过去的参数
this.$emit('ToSuper',this.childMsg);

2.在父组件中,使用v-on 监听时间名

<ChildTemplate superMsg='我是父组件内容' v-on:ToSuper='passParam'></ChildTemplate>

3.在父组件中实现,监听方法:

export default {
    name:'superTemplate',
    components:{
        ChildTemplate:ChildTemplate
    },
    data:function(){
        return {
            childMsg:''
        }
    },
    methods:{
        passParam:function(obj){
            this.childMsg = obj;
        }
    }
}
</script>

学习博客:

https://www.jianshu.com/p/89bd18e44e73

https://www.cnblogs.com/chenhongshuang/p/8678207.html

https://www.cnblogs.com/changwoo/p/9895670.html

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值