1、Prop 类型
https://cn.vuejs.org/v2/guide/components-props.html#Prop 类型
- String
- Number
- Boolean
- Array
- Object
- Date
- Function
- Symbol
props: ['title', 'likes', 'isPublished', 'commentIds', 'author']
不指定类型,则为String
props: { title: String, likes: Number, isPublished: Boolean, commentIds: Array, author: Object, callback: Function, contactsPromise: Promise // or any other constructor }
Prop 的大小写 (camelCase vs kebab-case)
camelCase (驼峰命名法) 的 prop 名需要使用其等价的 kebab-case (短横线分隔命名) 命名
Vue.component('blog-post', { // 在 JavaScript 中是 camelCase 的 props: ['postTitle'], template: '<h3>{{ postTitle }}</h3>' })
<!-- 在 HTML 中是 kebab-case 的 --> <blog-post post-title="hello!"></blog-post>
postTitle 再kebab-case命名为 post-title
组件实例的作用域是孤立的。这意味着不能(也不应该)在子组件的模板中直接饮用父组件的数据。要让子组件使用父组件的数据,需要通过子组件的 props 选项。
2、传递静态prop
传递静态prop
var ComponentB = {
props: ["post-title"],
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++" v-bind:title="postTitle">You clicked me {{ count }} times.</button>'
}
<component-b post-title="hello"></component-b>
运行结果:
<button title="hello!">You clicked me 0 times.</button>
3、动态prop
个人理解就是动态给Prop绑值
子组件中需要使用computed get得到
注:Props为单向数据流,父组件可以动态给Props设置值,但子组件中数据的改变不会影响父组件的数据。
new Vue({
el: '#app',
// 局部组件
components:{
'component-b': ComponentB,
'component-c':ComponentC,
},
data: {
testTitle:"23444444447"
}
)
<component-b post-title="testTitle"></component-b>
运行结构:
<button title="testTitle">You clicked me 0 times.</button>
4、Props 验证
PropOptions<T=any> {
type?: PropType<T>; // Props数据类型
required?: boolean; // 是否必填项
default?: T | null | undefined | (() => T | null | undefined); // 设置默认值
validator?(value: T): boolean;// 自定义验证函数
}