Vue的子組件props如何設置多個校驗類型
vue子組件props設置多個校驗值
1. type使用 | 進行隔開
props: { ? ? iconClass: { ? ? ? type: String | null, ? ? ? required: true, ? ? ? default: "" ? ? } },
2. 使用數(shù)組
props: { ? iconClass: [String , null] },
3. 使用validator校驗函數(shù)
props: { ?? ?iconClass: { ?? ? ? ?validator: (value)=> { ?? ? ? ? ?const getResult = Object.prototype.toString.call(value) ?? ? ? ? ?if(getResult === "[object Null]" || getResult === "[object String]") return true; ?? ? ? ?}, ?? ? ? ?required: true, ?? ? ? ?default: "" ? }, }
vue組件參數(shù)校驗
在vue中,當父組件向子組件傳遞值時.子組件可以對傳遞過來的值進行參數(shù)校驗.
首先我們定義一個子組件child,接受父組件傳遞過來的值content.
<child :content="1"></child> Vue.component('child',{ ? ? ? ? ? ? ? props:['content'], ? ? ? ? ? ? ? template: "<div>{{content}}</div>", ? ? ? ? ? })
注意但我們在content前面加上:,它會認為這是js表達式,所以認為"1"是Number類型而不是String類型.
參數(shù)校驗一
限定參數(shù)的類型
<child :content="1"></child> Vue.component('child',{ ? ? ? ? ? ? ? props:{ ? ? ? ? ? ? ? ?content: [String,Number], ? //這樣就限制了參數(shù)的類型為String或者Number. ? ? ? ? ? ? ?}, ? ? ? ? ? ? ? template: "<div>{{content}}</div>", ? ? ? ? ? })
如果不滿足則會報[Vue warn]: Invalid prop: type check failed for prop “content”. Expected String, got Number.
參數(shù)校驗二
限定參數(shù)的類型,是否必須,默認值
?Vue.component('child',{ ? ? ? ? ? ? ? props:{ ? ? ? ? ? ? ? ? ?content:{ ? ? ? ? ? ? ? ? ? ? ?type:Number, ? //限制參數(shù)的類型為Number ? ? ? ? ? ? ? ? ? ? ?default:100, ? //設置參數(shù)的默認值為100 ? ? ? ? ? ? ? ? ? ? ?required:false, ?//是否必須 ? ? ? ? ? ? ? ? ?}? ? ? ? ? ? ? ? }, ? ? ? ? ? ? ? template: "<div>{{content}}</div>", ? ? ? ? ? })
參數(shù)校驗三
自定義校驗規(guī)則
Vue.component('child',{ ? ? ? ? ? ? ? props:{ ? ? ? ? ? ? ? ? ?content:{ ? ? ? ? ? ? ? ? ? ? ?type:Number, ? ? ? ? ? ? ? ? ? ? ?default:100, ? ? ? ? ? ? ? ? ? ? ?required:false, ? ? ? ? ? ? ? ? ? ? ?validator:function(value){ ? //自定義校驗的規(guī)則 ? ? ? ? ? ? ? ? ? ? ? ? ?return value>5; ? ? ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? }, ? ? ? ? ? ? ? template: "<div>{{content}}</div>", ? ? ? ? ? })
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
解決vue數(shù)據(jù)更新但table內(nèi)容不更新的問題
這篇文章主要給大家介紹了vue數(shù)據(jù)更新table內(nèi)容不更新解決方法,文中有詳細的代碼示例供大家作為參考,感興趣的同學可以參考閱讀一下2023-08-08