prop 的背景
在前端分模块的应用中,会涉及到父子组件之间的数据传递,然后子组件接收到数据开始进行一些业务处理,这种场景下,使用vue props 就可以解决;
如何使用
- props 类型
props: { msg: String, age: Number, isPublished: Boolean, array: Array, obj: Object, callback: Function, contactsPromise: Promise }
- props可以支持静态 或者动态props, 那么可以传递那些类型数据
1.传递一个数字 age = "20"
2.传递boolean 值 is-published="false"
3.传递数组 array="[1,2,3]"
4.传递对象 obj = "obj"
上述列举为静态类型方式,如若传递动态的,可以增加v-bind: xx 支持,当然,我们更多的时候采用动态props 来传递,这样数据可以更加灵活;
下面通过增加一个demo 案例来感受下:
使用静态传递数据:
父组件定义:
<child msg="hello"></child>
子组件定义所接收的msg 属性:
props: {
msg: {
type:String,
default: ' '
}
},
<div>
<h1>child接收字符-msg {{ msg }}</h1>
</div>
使用动态传递数据 和静态传递区别在于父组件的数据传递增加v-bind 支持:
父组件定义:
<child v-bind:msg="msg"></child> msg 为动态变量,这样传递的数据更为灵活
- 子组件接收数据后如何改变props?
所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。这样会防止从子组件意外变更父级组件的状态。每次父级组件发生变更时,子组件中所有的 prop 都将会刷新为最新的值。为了能够在父组件中获取子组件变更后的值,下面列举了几种处理方案:
1.子组件中定义一个本地属性 childMessage,通过emit 将数据回传给父组件:子组件定义: <button @click="updateTitle()">child接收动态字符11-title {{ childMessage }}</button> props: { title: { type: String, default: '' } }, data: function () { return { childMessage:this.title } }, methods: { updateTitle:function(){ this.childMessage = this.childMessage.concat('test_update_title') //子组件内改变数据 console.log('updateTitle',this.childMessage) this.$emit('parentfunc',this.childMessage) //通过$emit 回传给父组件,这里parentfunc 为父组件定义的函数 } }
父组件定义: <child v-bind:title="title" @parentfunc="getChildTitle"></child> //定义接收的函数parentfunc methods: { getChildTitle(data){ console.log('父组件接收子组件传递的数据',data) //接收子组件更新后的数据回传 }
2.子组件可以对外提供一个获取数据方法,父组件通过ref 来获取子组件数据:
关于ref 说明: ref 被用来给元素或子组件注册引用信息, 引用信息会注册在父组件的$ref 对象上,如果作用在标签元素上,那么为一个dom 节点,如果作用在组件上,为一个组件实例;
子组件定义:
method:{
getValue(){
return this.transferInfo;
},
}
父组件中引入子组件:
<transfer-file :fileList="fileList" ref="TransferFile"></transfer-file>
method:{
getBasicValue(){
const transferInfo = this.$refs.TransferFile.getValue();
console.log('父组件中获取子组件的数据',transferInfo);
return this.transferInfo;
},
}
网友评论