Vue中props的使用詳解
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ù)進行處理。父組件的數(shù)據(jù)通過props傳入子組件以后,在子組件中也可對數(shù)據(jù)進行相關處理,包括計算屬性、data屬性等。這樣當子組件需要對數(shù)據(jù)進行處理時,避免了直接在父組件中對數(shù)據(jù)進行操作,而且由于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,而不能用字符串數(shù)組
Vue.component('example',{
props: {
propA: String,
propB: [Number,String]
}
});
總結
以上所述是小編給大家介紹的Vue中props的使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
vue2從數(shù)據(jù)變化到視圖變化之nextTick使用詳解
這篇文章主要為大家介紹了vue2從數(shù)據(jù)變化到視圖變化之nextTick使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09
vue與vue-i18n結合實現(xiàn)后臺數(shù)據(jù)的多語言切換方法
下面小編就為大家分享一篇vue與vue-i18n結合實現(xiàn)后臺數(shù)據(jù)的多語言切換方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03

