一、父组件通过props给子组件传值
- 在父组件的子组件标签上绑定一个属性,挂载要传输的变量。
- props就是父组件给子组件标签上定义的属性,用来接收父组件传递的数据,props的值可以是字符串数组,也可以是各自的名称和类型,用法和data中的数据用法一样,在子组件中只能使用该值,不能修改。
- 在子组件中通过props来接收数据,props可以是数组也可以是对象,接受的数据可以直接使用props:[“属性名”]或 props:{属性名:数据类型}
如: 1. props:["message"]
2. props:{
message:{
type: String,
default: "";
},
}
父组件通过props给子组件传值的示例如下:
//父组件
<template>
<div>
<son :height='height'></son> //3. 页面使用子组件 并将height值传递给子组件
</div>
</template>
<script>
import son from "./son.vue";// 1. 导入子组件
export default {
components:{ son }, // 2. 注册子组件
data(){
return {
height: "180----父组件传给子组件的值",
}
}
}
</script>
//子组件
<template>
<div>
{{height}} // 2. 使用父组件传过来的数据
</div>
</template>
<script>
export default {
props:{
height:[], // 1. 子组件通过props接收父组件传过来的数据
}
data(){
return {
}
}
}
</script>
二、子组件通过触发$emit事件给父组件传值
- 在父组件的子组件标签上自定义一个事件,然后调用需要的方法
- 在子组件的方法中通过this.$emit(“事件”)来触发在父组件中定义的事件,数据是以参数的形式进行传递的。
- $emit的第一个参数为自定义的事件,第二个参数为要传递给父组件的值,父组件在子组件的标签上绑定自定义事件来接收子组件传递的数据。
子组件通过触发$emit事件给父组件传值的示例如下:
//子组件
<template>
<div>
<button @click="clickMethod"></button>
</div>
</template>
<script>
export default {
data(){
return {
message:"给父组件传递的数据",
height:"180-----传递的数据"
}
},
methods:{
clickMethod(){
.....
// 1. 通过$emit将数据传递给父组件。
// 2. $emit的第一个参数为自定义的事件,第二个参数为要传递给父组件的值,
this.$emit("passParam",{this.message,this.height})
}
}
}
</script>
//父组件
<template>
<div>
<son
:height='height'
@passParam="getParam" //3. 页面使用子组件 通过子组件自定义的passParam事件,
></son> // 用getParam方法处理子组件传递过来的数据
</div>
</template>
<script>
import son from "./son.vue";// 1. 导入子组件
export default {
components:{ son }, // 2. 注册子组件
data(){
return {
height: "180----父组件传给子组件的值",
sonParam:'', //用于保存数据
}
},
methods:{
getParam(param){ // 4. 用getParam方法处理子组件传递过来的数据
this.sonParam=param;
}
}
}
</script>