8.2、props

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;// 自定义验证函数

}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值