Bootstrap

【Vue CLI脚手架开发】——3.组件交互props配置


前言

提示:这里可以添加本文要记录的大概内容:

例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。


提示:以下是本篇文章正文内容,下面案例可供参考

一、props数据接收方式

  1. 第一种方式(只接收):props:['name']

  2. 第二种方式(限制类型):props:{name:String}

  3. 第三种方式(限制类型、限制必要性、指定默认值):

     ```js
     props:{
     	name:{
     	type:String, //类型
     	required:true, //必要性
     	default:'老王' //默认值
     	}
     }
     ```
    

    备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。

二、代码实现

1. 父组件

App.vue

<template>
	<div>
		<Student :name="name" :sex="sex" ></Student>
		<hr>
		<School :schools="data_school" :userInfo="userInfo"></School>
	</div>
</template>

<script>
	import Student from './components/Student'
	import School from './components/School'

	export default {
		name:'App',
		components:{
			Student,
			School
		},
		data() {
			return {
				name:"张三",
				sex:"男",
				age:19,
				data_school:["清华","北大","浙大"],
				userInfo:{
					name:"小壮",
					age:18
         			}
			}
		},
	}
</script>

2.子组件

Student.vue

<template>
	<div>
		<h1>{{ msg }}</h1>
		<h2>学生姓名:{{name}}</h2>
		<h2>学生性别:{{sex}}</h2>
		<h2>学生年龄:{{myAge + 1}}</h2>
		<button @click="updateAge">尝试修改收到的年龄</button>
	</div>
</template>

<script>
	 export default {
		name:'Student',
		data(){
			return {
				msg:"欢迎来到vue学院",
				myAge: this.age
				
			}
		},
		methods: {
			updateAge(){
				this.myAge++
			}
		},
		//方式一:简单声明接收
		// props:['name','sex','age'] //变量顺序可以交换

		//方式二:接收的同时对数据进行类型限制
		// props:{
		// 	name:String,//限制name为String类型
		// 	age:Number,//限制age为Number类型
		// 	sex:String //限制sex为String类型
		// }

		//方式三:接收的同时对数据:进行类型限制+默认值的指定+必要性的限制
		props:{
			name:{
				type:String,//name的类型限制是String类型
				required:true //name是必须的
			},
			sex:{
				type:String, //sex限制为String类型
				required:true //sex是必须的
			},
			age:{
				type:Number,//限制age类型为String类型
				default:100 //默认值为18
			}
		}
	}
</script>

School.vue

<template>
	<div class="demo">
		<h2>学校名称:{{name}}</h2>
		<h2>学校地址:{{address}}</h2>
		<button @click="showName">展示学校</button>	
	</div>
</template>

<script>
	 export default {
		name:'School',
		props:{
			schools: {
         		//数组和对象必须使用函数返回
         			type: Array,
        			default: function() {
					return [];
         			},
       		},
			userInfo:{
          		type: Object,
          		default: function() {
               		return null;
          		}
       		}
		},

		data(){
			return {
				name:'vue学院',
				address:'上海黄浦区'
			}
		},
		methods: {
			showName(){
				console.log("schools ",this.schools)
				console.log("userInfo: ",this.userInfo)
			}
		},
	}
</script>

<style>
	.demo{
		background-color: orange;
	}
</style>

三、分析

在这里插入图片描述

在这里插入图片描述

注意:
①在父组件给Student子组件传递数据时,没有rb变量,子组件接收数据位undefined
②一般通过props接收的数据不要去修改,否则控制台会报警告错误,我们一般使用接收数据复制一份到data中,进行再修改。
在这里插入图片描述
①当接收的数据类型为数组和Object对象类型时,//default默认值需要给数组和对象必须使用函数返回。
②推荐接收数据props限制类型,使用方式二和方式三。

;