Vue学习笔记之父子组件通信
1,父组件往子组件传值使用props:
在使用props往子组件传值时,在子组件定义props,相当于一个自定义的属性,用来接收父组件中的数据,像是一个通道。在父组件中使用子组件时,直接在子组件上使用v-bind来绑定这个自定义的属性。
2,子组件往父组件传值使用
e
m
i
t
:
在
子
组
件
中
定
义
触
发
传
值
给
父
组
件
的
事
件
,
并
使
用
emit:在子组件中定义触发传值给父组件的事件,并使用
emit:在子组件中定义触发传值给父组件的事件,并使用emit将事件发送给父组件,父组件通过v-on监听该事件接收子组件传过来的值,完整代码如下
parent.vue
<template>
<div>我是父组件
<el-input v-model="parentMessage" ></el-input>
<el-input v-model="message"></el-input>
<br>
<br>
<br>
<p>在父组件中使用子组件</p>
<child @OK="getChildMessage" :parentMessage="parentMessage"></child>
</div>
</template>
<script>
import child from "./child";
export default {
components:{
child
},
name:'parent',
data(){
return{
parentMessage:'我是父组件的消息',
message:""
}
},
methods:{
// 监听子组件的触发事件
getChildMessage(message){
this.message=message
}
}
}
</script>
child.vue
<template>
<div>
我是子组件
<el-input v-model="message"></el-input>
<!-- 点击按钮发送消息给父组件 -->
<el-button @click="childClick" type="primary">发送</el-button>
<el-input v-model="parentMessage"></el-input>
</div>
</template>
<script>
export default {
name:'child',
//用prop接收父组件的值
props:{
parentMessage:{
type:String,
default:""
}
},
data(){
return {
message:"我是来自子组件的信息"
}
},
methods:{
childClick(){
this.$emit("OK",this.message)
}
}
}
</script>
运行效果图如下,
点击发送按钮