父子组件通信-父传子props
父子组件的通信
子组件是不能引用父组件或者Vue实例的数据的,但是在开发中,往往一些数据确实需要从上层传递到下层:
1.比如在一个页面中,我们从服务器请求到了很多的数据
2.其中一部分的数据,并非是我们整个页面的大组件来展示的,而是需要下面的子组件进行展示
3.这个时候,并不会让子组件再次发送一个网络请求,而是直接让大组件(父组件)将数据传递给小组件(子组件)
如何进行父子组件间的通信呢?Vue官方提到:
1.通过props向子组件传递数据
2.通过事件向父组件发送消息(自定义事件emit)
在真实开发中,Vue实例和子组件的通信和父组件和子组件的通信过程是一样的
props基本用法:
在组件中,使用选项props来声明需要从父级接收到的数据。
props的值有两种方式:
方式一:字符串数组,数组中的字符串就是传递时的名称
方式二:对象,对象可以设置传递时的类型,也可以设置默认值等
props数据验证
除了数组之外,也可以使用对象,当需要对props进行类型验证时,就需要对象写法了。
验证都支持哪些数据类型呢?
string
number
boolean
array
object
date
function
symbol
当我们有自定义的构造函数时,验证也支持自定义类型
栗子:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<cpn v-bind:cmovies="movies" ></cpn>
</div>
<template id="cpn">
<div>
<ul>
<li v-for="item in cmovies">{{item}}</li>
</ul>
<p>{{cmovies}}</p>
<h3>{{cmessage}}</h3>
</div>
</template>
<script src="../../vue.min.js"></script>
<script>
//父传子
const cpn={
template:'#cpn',
// props:['cmovies','cmessage'],
props:{
//1.类型限制
// cmovies:Array,
// cmessage:String,
//2.提供一些默认值,以及必传值
cmessage:{
type:String,
default:'aaaaaa',
required:true
},
cmovies:{
type: Array,
default(){
return []
},
required: true
}
},
data(){
return{}
},
methods:{}
}
const app=new Vue({
el:'#app',
data:{
message:'hello',
movies:['海王','海贼王','电锯惊魂']
},
components:{
cpn
}
})
</script>
</body>
</html>
props驼峰标识
想用驼峰标识就要用“ - ”隔开: :c-info=“info” :child-message=“message”
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<cpn :c-info="info" :child-message="message"></cpn>
</div>
<template id="cpn">
<div>
<h2>{{cInfo}}</h2>
<h2>{{childMessage}}</h2>
</div>
</template>
<script src="../../vue.min.js"></script>
<script>
const cpn={
template:'#cpn',
props:{
cInfo:{
type:Object,
default(){
return{}
}
},
childMessage:{
type: String,
default:'',
}
}
}
const app=new Vue({
el:'#app',
data:{
info:{
name:'Eli',
age:18,
height:1.88,
},
message:'hello',
},
components:{
cpn
}
})
</script>
</body>
</html>