1.子传父
父组件
<!--父组件-->
<template>
<div>
<p>子级接收的数据----{{name}}</p>
<!--子级事件 toParent-->
<com @toParent='resChild'></com>
</div>
</template>
<script>
import com from './com'
export default{
name:'page',
data(){
return {
name:'',
text:'page页面----',
data:['zhangsan','lisi','wangwu','zhaoliu']
}
},
components:{
com
},
mounted(){
},
methods:{
resChild(res){
console.log(res);
this.name=res;
},
}
}
</script>
子组件
<!--子组件-->
<template>
<div>
<z-button @click.native='bindtap'>点击触发子传父</z-button>
</div>
</template>
<script>
export default{
name:'com',
data(){
return {
msg:'这是子组件数据'
}
},
methods:{
bindtap(){
this.$emit('toParent',this.msg); //监听事件 需要传的值
}
}
}
</script>
2.使用作用域插槽slot-scope
父组件
<!--父组件-->
<template>
<div>
<com>
<!--com组件名-->
<!--将child定义为插槽作用域的名字-->
<template slot-scope='child'>
<p>接收到的子级数据----{{child.msgP}}</p>
</template>
</com>
</div>
</template>
<script>
import com from './com'
export default{
name:'page',
data(){
return {
}
},
components:{
com
}
}
</script>
子组件
<!--子组件-->
<template>
<div>
<!--父级接收字段 msgP 子级数据字段msg-->
<slot :msgP='msg'></slot>
</div>
</template>
<script>
export default{
name:'com',
data(){
return {
msg:'这是子组件数据'
}
}
}
</script>
3.slot-scope使用ES2015结构语法
父组件
<!--父组件-->
<template>
<div>
<com>
<!--com组件名-->
<!--使用ES2015结构语法-->
<template slot-scope='{msgP}'>
<p>接收到的子级数据0----{{msgP.key0}}</p>
</template>
</com>
</div>
</template>
<script>
import com from './com'
export default{
name:'page',
data(){
return {
}
},
components:{
com
}
}
</script>
子组件
<!--子组件-->
<template>
<div>
<!--父级接收字段 msgP 子级数据字段obj-->
<slot :msgP='obj'></slot>
</div>
</template>
<script>
export default{
name:'com',
data(){
return {
obj:{
key0:'第一个key',
key1:'第二个key'
}
}
}
}
</script>