1.自定義屬性props:即組件中聲明得屬性,子類接受父類得值 2.原聲屬性attrs:沒(méi)有聲明得屬性,默認(rèn)自動(dòng)掛在到組件根元素上,設(shè)置inheritAttrs為false能夠關(guān)閉自動(dòng)掛載 3.特殊屬性class,style掛載到組件根元素上,支持字符串,對(duì)象,數(shù)組等多種語(yǔ)法.
定義屬性得兩種方式 1.props: ['title', 'likes', 'isPublished', 'commentIds', 'author'] 無(wú)法對(duì)屬性值進(jìn)行校驗(yàn) 2.可以對(duì)屬性值進(jìn)行校驗(yàn)
props: { // 基礎(chǔ)得類型檢查 (`null` 和 `undefined` 會(huì)通過(guò)任何類型驗(yàn)證) propA: Number, // 多個(gè)可能得類型 propB: [String, Number], // 必填得字符串 propC: { type: String, required: true }, // 帶有默認(rèn)值得數(shù)字 propD: { type: Number, default: 100 }, // 帶有默認(rèn)值得對(duì)象 propE: { type: Object, // 對(duì)象或數(shù)組默認(rèn)值必須從一個(gè)工廠函數(shù)獲取 default: function () { return { message: 'hello' } } }, // 自定義驗(yàn)證函數(shù) propF: { validator: function (value) { // 這個(gè)值必須匹配下列字符串中得一個(gè) return ['success', 'warning', 'danger'].indexOf(value) !== -1 } } }
案例:
子組件
<template> <div> name:{{name}} <br/> type:{{type}} <br/> list:{{list}} <br/> isView:{{isView}} <br/> <button 等click="handClick">change</button> </div></template><script>export default { //子組件得名稱 name:"Props", props:{ name:String, type:{ validator:function(val){ return ["入門(mén)","小站","Rumenz"].includes(val) } }, list:{ type:Array, default:()=>[] }, isView:{ type:Boolean, default:false }, onChange:{ type:Function, default:()=>{} } }, methods:{ handClick(){ this.onChange(this.type==="入門(mén)"?"one":"tow") } }}</script><style></style>
父組件應(yīng)用子組件
<template><div id="app"> {{msg}} <!--屬性綁定格式 :[自組件得屬性]:[父組件得屬性]--> <Props :name="name" :type="type" :list="list" :isView="view" :onChange="onChange" /> </div></template><script>//導(dǎo)入子組件import Props from './components/Props'export default { name: 'App', data() { return { msg: "hello 入門(mén)小站", name:"name", type:"入門(mén)", list:['入門(mén)','小站'], view:true } }, methods: { onChange(val){ this.name=val; } }, components: { Props //必須聲明子組件 }}</script><style>#app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px;}</style>