vuejs組件參數校驗
阿新 • • 發佈:2018-09-16
特性 聲明 數組 字符 是否 校驗 顯示 code 對象 父組件向子組件傳遞一些參數,那麽子組件有權對這些參數進行一個校驗,這個就是組件參數校驗
需求:父組件傳遞過來的必須是個字符串,這個要怎麽去校驗呢
<div id=‘root‘> <child content=‘hello world‘></child> </div> <script> Vue.component(‘child‘,{ props:{ content:String }, template:‘<div>{{content}}</div>‘ })將接收的props定義稱對象,並指定類型,不以數組的形式接收參數 接收的數據是字符串類型 或者 數組類型,,都可以var vm = new Vue({ el:‘#root‘ }) </script>
props:{
content:[String, Number]
}
復雜的校驗
<div id=‘root‘> <child content=‘hello world‘></child> </div> <script> Vue.component(‘child‘,{ props:{ content:{ type:String,//數據類型 required:false,//是否是必傳 default:‘default content‘,//如果沒傳值,默認值 validator:function(val){//自定義校驗器,數據必須>5 return (val.length>5) } } }, template:‘<div>{{content}}</div>‘ }) var vm = newVue({ el:‘#root‘ }) </script>
非props特性 父組件向子組件傳遞參數,子組件沒有props這塊內容,所以就會報錯,不去接收,就沒法使用這個content 第二個特點是,子組件沒接收,對應的屬性值會顯示在標簽中,props特性不會顯示
vuejs組件參數校驗