文章目录
前言
本博客的内容很多都来自官网,现在只是把自己的一些理解写出来给大家一起讨论学习
Vue官网
系列文章目录,Vue学习目录,每一章都有代码例子说明
七、Vue组件通信-父组件给子组件传递参数
之前我们说,组件不能直接使用Vue实例的数据,但是实际开发过程,组件使用Vue实例的数据很正常
7.1 组件要怎样才能使用父组件的数据呢?
通过 Prop 向子组件传递数据
7.2 Prop 使用
1)props属性的值为数组
定义
在组件对象里使用props属性,然后直接定义数组,数组的对应的值就是获取的传参的对象。
const component1 = {
template: "#component1",
props: ['propsMessage','propsmessage1'],
}
使用
在使用组件的时候,我只要把这些定义好数组的值,当成是组件的属性值就可以直接传递参数了。(使用v-bind可以使用父组件的data数据)
<!-- 使用v-bind可以使用父组件的data数据 -->
<component1 v-bind:props-message=message propsmessage1='参数1'></component1>
完成的例子
<body>
<div id="app">
<component1 v-bind:props-message=message propsmessage1='参数1'></component1>
</div>
<template id="component1">
<div>
<h2>{{propsMessage}}</h2>
<h2>{{propsmessage1}}</h2>
</div>
</template>
</body>
<script src="../css/vue.js"></script>
<script>
const component1 = {
template: "#component1",
props: ['propsMessage','propsmessage1'],
}
const app = new Vue({
el: '#app',
data: {
message: "你好"
},
components: {
'component1': component1
}
})
</script>
展示效果:
2)props属性的值为对象
对象的用处:允许配置高级选项,如类型检测、自定义验证和设置默认值。
你可以基于对象的语法使用以下选项:
对象属性值 | 说明 |
---|---|
type | 可以是下列原生构造函数中的一种:String、Number、Boolean、Array、Object、Date、Function、Symbol、任何自定义构造函数、或上述内容组成的数组。会检查一个 prop 是否是给定的类型,否则抛出警告。 |
default:any | 为该 prop 指定一个默认值。如果该 prop 没有被传入,则换做用这个值。对象或数组的默认值必须从一个工厂函数返回。 |
required:Boolean | 定义该 prop 是否是必填项。在非生产环境中,如果这个值为 truthy 且该 prop 没有被传入的,则一个控制台警告将会被抛出。 |
validator:Function | 自定义验证函数会将该 prop 的值作为唯一的参数代入。在非生产环境下,如果该函数返回一个 falsy 的值 (也就是验证失败),一个控制台警告将会被抛出 |
定义
和组数差不多,props属性是最大的一层对象,属性值是传递参数对象,然后可以对传递参数进行各种个性化设置
const component1 = {
template: "#component1",
props: {
// 检测类型
propsMessage: String,
height: String,
// 检测类型 + 其他验证
age: {
type: Number,
default: 0,
required: true,
validator: function (value) {
return value >= 0
}
}
}
}
使用
在使用组件的时候,我只要把这些定义对象属性值当成是组件的属性值就可以直接传递参数了。(使用v-bind可以使用父组件的data数据)
<div id="app">
<component1 v-bind:props-message=message height="哈哈" age=-1></component1>
<!--如果使用v-bind会识别不了data的数据-->
<!-- <component1 props-message=message></component1>-->
</div>
完成的例子
<body>
<div id="app">
<component1 v-bind:props-message=message height="哈哈" age=-1></component1>
<!--如果使用v-bind会识别不了data的数据-->
<!-- <component1 props-message=message></component1>-->
</div>
<template id="component1">
<div>
<h2>{{propsMessage}}</h2>
<h2>{{height}}</h2>
<h2>{{age}}</h2>
</div>
</template>
</body>
<script src="../css/vue.js"></script>
<script>
const component1 = {
template: "#component1",
props: {
// 检测类型
propsMessage: String,
height: String,
// 检测类型 + 其他验证
age: {
type: Number,
default: 0,
required: true,
validator: function (value) {
return value >= 0
}
}
}
}
const app = new Vue({
el: '#app',
data: {
message: "你好"
},
components: {
'component1': component1
}
})
</script>
展示效果: