props屬性是父子組件之間的通信橋梁。何為父子組件?從子組件的觀點來看,他的上一級實例或組件即為他的父組件。我們知道,處于安全考慮,組件模板里我們無法直接使用父組件的data數(shù)據(jù),使用props這個屬性可以將父組件的數(shù)據(jù)傳給子組件。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>props的測試</title> <script src="../js/vue.js"></script></head><body><div id="props"> <Child message="父組件的message,我把他的內(nèi)容重新定義了,但是父組件不會發(fā)生改變哦,因為沒有綁定,哈哈!!"></Child> <hr /> <input v-model="message"/> <Child :message='message'></Child></div><script> Vue.component('Child',{ props: ['message'], template: '<span>{{ message }}</span>' }); var vm = new Vue({ el: '#props', data: { message: 'prop的測試' } });</script></body></html>代碼效果圖
在子組件中對父組件的數(shù)據(jù)進(jìn)行處理。父組件的數(shù)據(jù)通過props傳入子組件以后,在子組件中也可對數(shù)據(jù)進(jìn)行相關(guān)處理,包括計算屬性、data屬性等。這樣當(dāng)子組件需要對數(shù)據(jù)進(jìn)行處理時,避免了直接在父組件中對數(shù)據(jù)進(jìn)行操作,而且由于props數(shù)據(jù)流單向性,在子組件中更改數(shù)據(jù)時,不會對父組件的數(shù)據(jù)產(chǎn)生影響。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>props的測試</title> <script src="../js/vue.js"></script></head><body><div id="props"> <input v-model="message"/> <Child :message='message'></Child></div><script> Vue.component('Child',{ props: ['message','todos'], template: '<span>{{ test }}</span>', computed: { test: function(){ return this.message.trim().toUpperCase(); }} }); var vm = new Vue({ el: '#props', data: { message: 'prop的測試' } });</script></body></html>代碼效果圖
代碼效果圖
prop的驗證
我們可以為組件的 prop 指定驗證規(guī)則。如果傳入的數(shù)據(jù)不符合要求,Vue 會發(fā)出警告。這對于開發(fā)給他人使用的組件非常有用。
要指定驗證規(guī)則,需要用對象的形式來定義 prop,而不能用字符串?dāng)?shù)組
Vue.component('example',{ props: { propA: String, propB: [Number,String]}});總結(jié)
以上所述是小編給大家介紹的Vue中props的使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對錯新站長站網(wǎng)站的支持!
新聞熱點
疑難解答
圖片精選