1.自定义属性props:即组件中声明的属性,子类接受父类的值
2.原声属性attrs:没有声明的属性,默认自动挂在到组件根元素上,设置inheritAttrs为false能够关闭自动挂载
3.特殊属性class,style挂载到组件根元素上,支持字符串,对象,数组等多种语法.
定义属性的两种方式
1.props: [‘title’, ‘likes’, ‘isPublished’, ‘commentIds’, ‘author’] 无法对属性值进行校验
2.可以对属性值进行校验
props: {
// 基础的类型检查 (`null` 和 `undefined` 会通过任何类型验证)
propA: Number,
// 多个可能的类型
propB: [String, Number],
// 必填的字符串
propC: {
type: String,
required: true
},
// 带有默认值的数字
propD: {
type: Number,
default: 100
},
// 带有默认值的对象
propE: {
type: Object,
// 对象或数组默认值必须从一个工厂函数获取
default: function () {
return { message: 'hello' }
}
},
// 自定义验证函数
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>
父组件应用子组件
<template>
<div id="app">
{{msg}}
<!--属性绑定格式 :[自组件的属性]:[父组件的属性]-->
<Props
:name="name"
:type="type"
:list="list"
:isView="view"
:onChange="onChange"
/>
</div>
</template>
<script>
//导入子组件
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>
源码:https://github.com/mifunc/rumenz-vue/tree/master/rumenz-vue-three-core