在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