vue学习--Props

Props:
        props用以从父组件接收数据:         
            使用:
                Vue.component('child',{
                    props:['msg'],
                    template:'<span>{{msg}}</span>'
                });
            声明:
                <child msg='hello!'></child>            // 字面量语法
                <child v-bind:msg='parentMsg'></child>    // 动态语法
            *如果props是myMsg, html中需要用my-msg(即:camelCase - kebab-case, 因为html的特性是不区分大小写)
            *字面量和动态语法稍有不同
                <comp some-prop="1"></comp>        // 传递了一个字符串 "1"
                <comp :some-prop="1"></comp>    // 传递实际的数字
    
    Props绑定类型:
        <child :msg="parentMsg"></child>        // 默认为单向绑定
        <child :msg.sync="parentMsg"></child>    // 双向绑定
        <child :msg.once="parentMsg"></child>    //单次绑定
        *如果prop是一个对象或数组,是按引用传递。不管使用哪种绑定方式,都将是双向绑定
    
    Props验证:
        props:{            // 此时props是一个对象
            propA: Number,
            propB:{
                type: String,                    // 类型(原生构造器:String, Number, Boolean, Function, Object, Array)
                required: true,                    // 是否必须项
                default: 'thyiad',                // 默认值(如果是Object, 默认值需由一个函数返回)
                validator: function(value){        // 验证
                    return value === 'thyiad';    
                },
                coerce:function(val){
                    return val+'';                // 将值强制转换为字符串
                    return JSON.parse(val);        // 将JSON字符串转换为对象
                }
            }
        }

posted @ 2017-11-28 09:38  青青子衿619  阅读(294)  评论(0编辑  收藏  举报