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

2023-05-12,,

组件中,使用选项props来声明需要从父级接收到的数据。
props的值有两种方式:
方式一:字符串数组,数组中的字符串就是传递时的名称。
方式二:对象,对象可以设置传递时的类型,也可以设置默认值等。
 <div id="app">
<!--<cnp :cinfo="info" :childMyMessage ="message"></cnp>-->
<!--在传值的时候不支持驼峰写法childMyMessage 要写成下面这种child-my-message-->
<cnp :cinfo="info" :child-my-message ="message"></cnp>
</div> <template id="cnp">
<!--VUE组件必须要有一个根元素包裹其他的标签元素-->
<div>
<h2>{{cinfo}}</h2>
<h2>{{childMyMessage}}</h2>
</div>
</template> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const cnp = {
template: '#cnp',
props: { //props单向数据流,父组件传递到子组件的值不允许直接改变
cinfo: {
type: object,
default(){ //默认值
return{}
}
},
childMyMessage: {
type: string,
default: ''
}
}
}
const app = new Vue ({
el: '#app',
data: {
info: {
name: 'why',
age: 18,
height: 1.88
},
message: 'aaaaa'
},
components: {
cnp
}
})
</script>
除了数组之外,我们也可以使用对象,当需要对props进行类型等验证时,就需要对象写法了。
验证都支持哪些数据类型呢?
String
Number
Boolean
Array
Object
Date
Function
Symbol
当我们有自定义构造函数时,验证也支持自定义的类型

Vue学习笔记-组件通信-父传子(props中的驼峰标识)的相关教程结束。

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

下载本文的Word格式文档,以方便收藏与打印。