欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue中props的使用詳解

 更新時(shí)間:2018年06月15日 16:53:11   作者:南北北南  
props屬性是父子組件之間的通信橋梁。這篇文章主要介紹了Vue中props的使用,需要的朋友可以參考下

props屬性是父子組件之間的通信橋梁。何為父子組件?從子組件的觀點(diǎn)來看,他的上一級實(shí)例或組件即為他的父組件。我們知道,處于安全考慮,組件模板里我們無法直接使用父組件的data數(shù)據(jù),使用props這個(gè)屬性可以將父組件的數(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)容重新定義了,但是父組件不會(huì)發(fā)生改變哦,因?yàn)闆]有綁定,哈哈??!"></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)處理,包括計(jì)算屬性、data屬性等。這樣當(dāng)子組件需要對數(shù)據(jù)進(jìn)行處理時(shí),避免了直接在父組件中對數(shù)據(jù)進(jìn)行操作,而且由于props數(shù)據(jù)流單向性,在子組件中更改數(shù)據(jù)時(shí),不會(huì)對父組件的數(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的驗(yàn)證

 我們可以為組件的 prop 指定驗(yàn)證規(guī)則。如果傳入的數(shù)據(jù)不符合要求,Vue 會(huì)發(fā)出警告。這對于開發(fā)給他人使用的組件非常有用。

要指定驗(yàn)證規(guī)則,需要用對象的形式來定義 prop,而不能用字符串?dāng)?shù)組

Vue.component('example',{
  props: {
    propA: String,
    propB: [Number,String]
}
});

總結(jié)

以上所述是小編給大家介紹的Vue中props的使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評論