1、父传子
父组件自定义个title属性,绑定要传递的值,子组件通过一个props实例把父组件传递的值获取就可以渲染了。
<template>
<div>
<p>父组件</p>
<con :title="hello"/>
</div>
</template>
<script>
import con from '../components/componts.vue'
export default {
name:'login',
data(){
return{
hello:"你的父亲组件"
}
},
components:{
con
}
}
</script>
子组件
<template>
<div class="hello">
{{title}}
</div>
</template>
<script>
export default {
name: 'Compont',
data(){
return{}
},
props:{
title:String
}
}
</script>
注:子组件接受父组件传递过来的是可以定义变量的类型,不是符合类型就不接收
2、子传父
子组件通过点击事件,在点击事件里面自定义个事件
this.$emit(“getdata”,this.test)然后传递给父组件,
父组件接受这个子组件自定义的事件,这个事件有个里面的返回值就是传递过来的数据
<con @getdata=“getdata”/>
子组件
<template>
<div class="hello">
<button @click="opee">子传父</button>
</div>
</template>
<script>
export default {
name: 'Compont',
data(){
return{
test:"我是儿孩子组件"
}
},
methods:{
opee:function(){
this.$emit("getdata",this.test)
}
},
}
</script>
父组件
<template>
<div>
<p>父组件</p>
{{msg}}
<con @getdata="getdata"/>
</div>
</template>
<script>
import con from '../components/componts.vue'
export default {
name:'login',
data(){
return{
msg:"父组件本来的值"
}
},
methods:{
getdata(e){
this.msg=e
console,log(e)
}
},
components:{
con
}
}
</script>