vue父子组件通信【props、emit】
1、父组件给子组件传参【props】
(1)传递单个参数
parent.vue //父组件
<template>
<div>
父组件:向子组件传参
<Child
:city ='city'
></Child>
</div>
</template>
<script>
import Child from "./child";
export default {
name: "parent",
components: {
Child
},
data(){
return{
city:"北京",
}
}
}
</script>
child.vue //子组件
<template>
<div>
子组件:这是父组件向我传递的参数:城市:{{city}}
</div>
</template>
<script>
export default {
name: "child",
props:{
city: {
type: String, // 数据类型
default: "", // 默认值
},
}
}
</script>
(2)传递obj对象
parent.vue //父组件
<template>
<div>
父组件:向子组件传参
<Child
v-bind ='obj'
></Child>
</div>
</template>
<script>
import Child from "./child";
export default {
name: "parent",
components: {
Child
},
data(){
return{
obj:{
name:"程序猿~~",
age:'22',
},
}
}
}
</script>
child.vue //子组件
<template>
<div>
子组件:这是父组件向我传递的对象:名称:{{name}}----年龄:{{age}}
</div>
</template>
<script>
export default {
name: "child",
props:{
name: {
type: String, // 数据类型
default: "", // 默认值
},
age: {
type: [String, Number], //类型可以是多种
validator: function (value) { //自定义验证
let num = parseInt(value)
if (num > 0 && num < 160) {
return true;
} else {
return false;
}
}
},
default: 22, // 默认值
}
}
</script>
(3)props的单向数据传递,直接作为一个本地变量
parent.vue //父组件
<template>
<div>
<input type="text" v-model="content">下面是子组件
<Child
:content="content"
></Child>
</div>
</template>
<script>
import Child from "./child";
export default {
name: "parent",
components: {
Child
},
data(){
return{
content:"啦啦啦",
}
}
}
</script>
child.vue //子组件
<template>
<div>
子组件:这是父组件向我传递的数据:{{con}}
</div>
</template>
<script>
export default {
name: "child",
props:['content'],
data(){
return{
con:this.content
}
}
}
}
</script>
2、子组件给父组件传参【emit】
子组件向父组件传递数据,不能像上面一样实时的进行传递,必须通过事件去进行触发,所以我们通过$emit方法向父组件传递数据;第一个参数是触发事件的名称,第二个为传递的数据。
parent.vue //父组件
<template>
<div>
父组件:这是我的子组件传给我的值:{{num}}
<Child
:content="content"
@getNum='getMsg'
></Child>
</div>
</template>
<script>
import Child from "./child";
export default {
name: "parent",
components: {
Child
},
data(){
return{
num:'',
}
},
methods:{
getMsg(num){
this.num = num;
}
},
}
</script>
child.vue //子组件
<template>
<div>
子组件:这是父组件向我传递的数据:{{content}} <br/>
<button @click="sendMsgtoParent">点击我向父子间传递参数</button>
</div>
</template>
<script>
export default {
name: "child",
props:{
content:['content'],
data(){
return{
num:0
}
},
methods: {
sendMsgtoParent(){
this.$emit('getNum',this.num ++)
}
}
}
}
</script>