Vue-父组件向子组件传值
下面示例中是:父组件向子组件的单向数据流
父级的更新会向下流动到子组件中,但是反过来则不行。每次父级组件发生更新时,子组件中所有的prop都将会刷新为最新的值。
一、在父组件中引入、注册、调用、传值子组件
1.引入:import son from "../son";
2.注册:components: { son }
3.调用:<son></son>
4.传值:<son :fatherToSonParaText="fathertext" :fatherToSonParaJosn="fatherJson" ></son>
说明:"son"名称需要规范,否则可能异常
<template>
<div>
<div><span>父组件</span></div>
<div>
<son :fatherToSonParaText="fathertext" :fatherToSonParaJosn="fatherJson" ></son>
</div>
</div>
</template>
<script>
import son from "../son";
export default {
components: {
son
},
data() {
return {
fathertext: "aaaaaaaaaaaaaaaaa",
fatherJson:{
item1:"item1",
item2:"item2",
item3:"item3",
},
};
},
};
</script>
二、子组件定义props接收参数
1.接收参数:使用props属性,参数名称fatherToSonParaText / fatherToSonParaJosn 需要和父组件绑定的名称一致
2.参数可以声明参数类型String、Number、Boolean、Array、Object、Date、Function、Symbol
<template>
<div>
<div>{{"父组件传入值:" + fatherToSonParaText}}</div>
<div>---------------------------------------------</div>
<div>{{"父组件传入值:" + fatherToSonParaJosn.item1}}</div>
</div>
</template>
<script>
export default {
props: {
fatherToSonParaText: {
type: String,
default:"",
required: true
},
fatherToSonParaJosn: {
type: Object,
default:{},
required: true
}
},
data() {
return {
SonParaText:"",
SonParaJosn:{},
};
},
methods: {
init() {
this.SonParaText = this.fatherToSonParaText;
this.SonParaJosn = this.fatherToSonParaJosn;
}
},
mounted() {
this.init();
}
};
</script>