Vue的子組件props如何設(shè)置多個(gè)校驗(yàn)類型
vue子組件props設(shè)置多個(gè)校驗(yàn)值
1. type使用 | 進(jìn)行隔開
props: { ? ? iconClass: { ? ? ? type: String | null, ? ? ? required: true, ? ? ? default: "" ? ? } },
2. 使用數(shù)組
props: { ? iconClass: [String , null] },
3. 使用validator校驗(yàn)函數(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ù)校驗(yàn)
在vue中,當(dāng)父組件向子組件傳遞值時(shí).子組件可以對(duì)傳遞過來的值進(jìn)行參數(shù)校驗(yàn).
首先我們定義一個(gè)子組件child,接受父組件傳遞過來的值content.
<child :content="1"></child> Vue.component('child',{ ? ? ? ? ? ? ? props:['content'], ? ? ? ? ? ? ? template: "<div>{{content}}</div>", ? ? ? ? ? })
注意但我們?cè)赾ontent前面加上:,它會(huì)認(rèn)為這是js表達(dá)式,所以認(rèn)為"1"是Number類型而不是String類型.
參數(shù)校驗(yàn)一
限定參數(shù)的類型
<child :content="1"></child> Vue.component('child',{ ? ? ? ? ? ? ? props:{ ? ? ? ? ? ? ? ?content: [String,Number], ? //這樣就限制了參數(shù)的類型為String或者Number. ? ? ? ? ? ? ?}, ? ? ? ? ? ? ? template: "<div>{{content}}</div>", ? ? ? ? ? })
如果不滿足則會(huì)報(bào)[Vue warn]: Invalid prop: type check failed for prop “content”. Expected String, got Number.
參數(shù)校驗(yàn)二
限定參數(shù)的類型,是否必須,默認(rèn)值
?Vue.component('child',{ ? ? ? ? ? ? ? props:{ ? ? ? ? ? ? ? ? ?content:{ ? ? ? ? ? ? ? ? ? ? ?type:Number, ? //限制參數(shù)的類型為Number ? ? ? ? ? ? ? ? ? ? ?default:100, ? //設(shè)置參數(shù)的默認(rèn)值為100 ? ? ? ? ? ? ? ? ? ? ?required:false, ?//是否必須 ? ? ? ? ? ? ? ? ?}? ? ? ? ? ? ? ? }, ? ? ? ? ? ? ? template: "<div>{{content}}</div>", ? ? ? ? ? })
參數(shù)校驗(yàn)三
自定義校驗(yàn)規(guī)則
Vue.component('child',{ ? ? ? ? ? ? ? props:{ ? ? ? ? ? ? ? ? ?content:{ ? ? ? ? ? ? ? ? ? ? ?type:Number, ? ? ? ? ? ? ? ? ? ? ?default:100, ? ? ? ? ? ? ? ? ? ? ?required:false, ? ? ? ? ? ? ? ? ? ? ?validator:function(value){ ? //自定義校驗(yàn)的規(guī)則 ? ? ? ? ? ? ? ? ? ? ? ? ?return value>5; ? ? ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? }, ? ? ? ? ? ? ? template: "<div>{{content}}</div>", ? ? ? ? ? })
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue2.0使用過程常見的一些問題總結(jié)學(xué)習(xí)
本篇文章主要介紹了Vue2.0使用過程常見的一些問題總結(jié)學(xué)習(xí),詳細(xì)的介紹了使用中會(huì)遇到的各種錯(cuò)誤,有興趣的可以了解一下。2017-04-04vue導(dǎo)出html、word和pdf的實(shí)現(xiàn)代碼
這篇文章主要介紹了vue導(dǎo)出html、word和pdf的實(shí)現(xiàn)方法,文中完成了三種文件的導(dǎo)出但是還有很多種方法,小編就不給大家一一列舉了,需要的朋友可以參考下2018-07-07解決vue數(shù)據(jù)更新但table內(nèi)容不更新的問題
這篇文章主要給大家介紹了vue數(shù)據(jù)更新table內(nèi)容不更新解決方法,文中有詳細(xì)的代碼示例供大家作為參考,感興趣的同學(xué)可以參考閱讀一下2023-08-08vue?如何綁定disabled屬性讓其不能被點(diǎn)擊
這篇文章主要介紹了vue?如何綁定disabled屬性讓其不能被點(diǎn)擊,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04vue.js移動(dòng)數(shù)組位置,同時(shí)更新視圖的方法
下面小編就為大家分享一篇vue.js移動(dòng)數(shù)組位置,同時(shí)更新視圖的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03