Vue学习笔记-组件通信-父传子(props中的驼峰标识)

在组件中,使用选项props来声明需要从父级接收到的数据。
props的值有两种方式:
方式一:字符串数组,数组中的字符串就是传递时的名称。
方式二:对象,对象可以设置传递时的类型,也可以设置默认值等。

 1 <div id="app">
 2     <!--<cnp :cinfo="info" :childMyMessage ="message"></cnp>-->
 3     <!--在传值的时候不支持驼峰写法childMyMessage 要写成下面这种child-my-message-->
 4     <cnp :cinfo="info" :child-my-message ="message"></cnp>
 5 </div>
 6 
 7 <template id="cnp">
 8     <!--VUE组件必须要有一个根元素包裹其他的标签元素-->
 9     <div>
10         <h2>{{cinfo}}</h2>
11         <h2>{{childMyMessage}}</h2>
12     </div>
13 </template>
14 
15 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
16 <script>
17     const cnp = {
18         template: '#cnp',
19         props: { //props单向数据流,父组件传递到子组件的值不允许直接改变
20             cinfo: {
21                 type: object,
22                 default(){ //默认值
23                     return{}
24                 }
25             },
26             childMyMessage: {
27                 type: string,
28                 default: ''
29             }
30         }
31     }
32     const app = new Vue ({
33         el: '#app',
34         data: {
35             info: {
36                 name: 'why',
37                 age: 18,
38                 height: 1.88
39             },
40             message: 'aaaaa'
41         },
42         components: {
43             cnp
44         }
45     })
46 </script>

 

除了数组之外,我们也可以使用对象,当需要对props进行类型等验证时,就需要对象写法了。
验证都支持哪些数据类型呢?
String
Number
Boolean
Array
Object
Date
Function
Symbol
当我们有自定义构造函数时,验证也支持自定义的类型

 

 

 

posted @ 2019-11-21 16:12  leahtao  阅读(647)  评论(0编辑  收藏  举报