Vue props向子組件中傳遞數據
聲明組件對象中定義 props
1、在聲明組件對象中使用 props 選項指定
const MyComponent = {
template:'<div></div>',
props: 此處值有以下3中方式,
components:{
}
}
方式一:指定傳遞屬性名,注意是數組形式。
props:['id','name','sarlary','isPublished']
方式二:指定屬性名和數據類型,注意是對象形式。
props:{
id:Number,
name:String,
salary:Number,
isPublished:Boolean,
commentIds:Array,
author:Object,
getEmp:Function
}
方式三:指定屬性名、數據類型、必要性、默認值。
props:{
name:{
type:String,
required:true,
default:'wjw'
}
}
引用組件時動態賦值
在引用組件時,通過 v-bind 動態賦值
<my-component v-bind:id="2" :name="wangjiawei" :salary="9999" :is-published="true" :comment-ids="[1,2]" :author="{name:'alan'}" :get-emp="getEmp">
</my-component>
傳遞數據注意
- props 值用於父組件向子組件傳遞數據。
- 所有標簽屬性都會成為組件對象的屬性,模板頁面可以直接引用。
- 問題:
a. 如果需要向非子后代傳遞數據,必須是多層逐層傳遞。
b. 兄弟組件間也不能直接 props 通信,必須借助父組件才可以。