Vue基礎篇: 組件參數校驗與非props屬性

1、組件的參數校驗
  • 子組件如何對組件進行約束

父組件經過屬性的方式對子組件傳遞內容數據,而子組件經過props的方式對數據進行接收,這時,子組件能夠組件中的props傳參的規則,設定屬性的數據類型:bash

單一數據類型的參數校驗

如: 指定content必須爲字符串app

<div id="app">
         <child content="hello world"></child>        
    </div>

    Vue.component('child', {
        props:{
        	content:String
        },
        template: '<div>{{content}}</div>',
        data() {
            return {
                message: '這是一個實例數據'
            }
        }
    })
複製代碼
多種數據類型的參數校驗

如: 指定content能夠爲字符串或者數字類型dom

Vue.component('child', {
        props:{
        	content:[String,Number]
        },
        template: '<div>{{content}}</div>',
        data() {
            return {
                message: '這是一個實例數據'
            }
        }
    })
複製代碼
複雜的參數校驗

props: 接收屬性,爲一個對象,能夠設置參數ui

type:表示所傳數據的類型

required:true(表示該屬性是必傳)

default: 'default' (提醒父組件並無該屬性傳遞)

validator (自定義校驗器,表示對傳入屬性的進行校驗)
複製代碼

以下:this

Vue.component('child', {
        props:{
        	content:{
        		type:String, //表示類型必須爲 String
        		required:true, //true 表示屬性必傳  false表示能夠不傳屬性
        		default:'默認內容',  //提醒父組件並無屬性傳遞
        		validator:function(res){
        			 return (res.length >5 ) //自定義校驗器,表示對傳入屬性的進行校驗長度
        		}
        	}
        },
        template: '<div>{{content}}</div>',
        data() {
            return {
                message: '這是一個實例數據'
            }
        }
    })
複製代碼
2、非props特性

非props 特性,父組件經過屬性向子組件傳遞數據時,在子組件接收時,並無聲明props屬性來接收數據spa

<div id="app">
         <child content="hello world"></child>        
    </div>

  Vue.component('child', {
        template: '<div>{{content}}</div>',
        data() {
            return {
                message: '這是一個實例數據'
            }
        }
    })
複製代碼

會出錯:父組件中的content未被定義code

其特色以下:component

一、組件未定義props進行接收父組件屬性傳來的值,那麼這個屬性(如content)則爲非props特性。

二、父組件使用一個非props特性,子組件沒有經過props接收屬性數據,該屬性則會展示在子組件template中的頁面模板的dom標籤的屬性中。
複製代碼
3、props特性

props特性,父組件經過屬性向子組件傳遞數據時,在子組件接收時,在props中聲明接收了這個屬性數據對象

<div id="app">
         <child content="hello world"></child>        
    </div>

  Vue.component('child', {
        props:['content'],
        template: '<div>{{content}}</div>',
        data() {
            return {
                message: '這是一個實例數據'
            }
        }
    })
複製代碼

其特色以下:字符串

1. 子組件所帶的屬性傳遞是不會出如今dom上
 
 2. 父組件經過屬性傳值後,子組件就會經過template中的插值表達式或者經過this.content去取得該屬性中的內容
複製代碼
相關文章
相關標籤/搜索