1.自定義屬性props:即組件中聲明得屬性,子類接受父類得值 2.原聲屬性attrs:沒有聲明得屬性,默認自動掛在到組件根元素上,設(shè)置inheritAttrs為false能夠關(guān)閉自動掛載 3.特殊屬性class,style掛載到組件根元素上,支持字符串,對象,數(shù)組等多種語法.
定義屬性得兩種方式 1.props: ['title', 'likes', 'isPublished', 'commentIds', 'author'] 無法對屬性值進行校驗 2.可以對屬性值進行校驗
props: { // 基礎(chǔ)得類型檢查 (`null` 和 `undefined` 會通過任何類型驗證) propA: Number, // 多個可能得類型 propB: [String, Number], // 必填得字符串 propC: { type: String, required: true }, // 帶有默認值得數(shù)字 propD: { type: Number, default: 100 }, // 帶有默認值得對象 propE: { type: Object, // 對象或數(shù)組默認值必須從一個工廠函數(shù)獲取 default: function () { return { message: 'hello' } } }, // 自定義驗證函數(shù) propF: { validator: function (value) { // 這個值必須匹配下列字符串中得一個 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 ["入門","小站","Rumenz"].includes(val) } }, list:{ type:Array, default:()=>[] }, isView:{ type:Boolean, default:false }, onChange:{ type:Function, default:()=>{} } }, methods:{ handClick(){ this.onChange(this.type==="入門"?"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 入門小站", name:"name", type:"入門", list:['入門','小站'], 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>