## props配置项
1. 功能:让组件接收外部传过来的数据
2. 传递数据:```<Demoname="xxx"/>```
3. 接收数据:
1. 第一种方式(只接收):```props:['name'] ```
2. 第二种方式(限制类型):```props:{name:String}```
3. 第三种方式(限制类型、限制必要性、指定默认值):
```js
props:{
name:{
type:String, //类型
required:true, //必要性
default:'老王' //默认值
}
}
```
> 备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。
Student.vue:
<template>
<div >
<h1>{{ msg }}</h1>
<h2>学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<h2>学生年龄:{{myAge}}</h2>
<button @click="update">点我age +1</button>
</div>
</template>
<script>
export default {
name:'s-student',
data() {
return {
msg:'我是一个学生',
myAge:this.age
}
},
methods:{
update(){
this.myAge++
}
},
//一般开发中用简单声明
//props:['name','sex','age']//简单声明接收:顺序不一定要一样
//接受的同时对数据进行限制
/*props:{
name:String,
age:Number,
sex:String
}*/
//接受的同时对数据进行限制、默认值的指定,必要性的限制
props:{
name:{
type:String,//类型为字符串
required:true//必须传入
},
age:{
type:Number,
default:0//可以不传入,默认值为0
},
sex:{
type:String,
required:true
}
}
}
</script>
<template>
<div>
<!--:表示动态绑定,能够传入数字类型的值-->
<Student name="Gui" sex="female" :age="19"/>
<Student name="Liu" sex="male" :age="20"/>
</div>
</template>
<script>
//引入School组件
import Student from './components/Student'
export default {
name:'App',
components:{Student},
}
</script>