iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 28
0
自我挑戰組

從0開始vue.js的30天學習日誌系列 第 28

28 Vue組件 - props(2)

上一篇學習使用props接收上層傳來的資料( 字串 ),今天來學習如何動態綁定props:

使用v-bind :動態綁定

<div id="app">
  <test :text="text"></test>
</div>

<script>
new Vue({
  el:"#app",
  data:{
    text:"hello",
  },
  components:{
    test:{
      props:["text"],
      template: "<div>{{text}}</div>"
    }
  }
  
});
</script>

使用v-for

<div id="app">
  <test v-for="text in strings" :text="text"></test>
</div>

<script>
new Vue({
  el:"#app",
  data:{
    strings:["str1", "str2"]
  },
  components:{
    test:{
      props:["text"],
      template: "<div>{{text}}</div>"
    }
  }
  
});
</script>

當data為物件

沿用上面範例當data是物件時,props指定對應的值string.namestrings.email,成功render出兩組人名及email:

<div id="app">
  <test v-for="text in posts" :name="text.name" :email="text.email"></test>
</div>

<script>
new Vue({
  el:"#app",
  data:{
    posts:[
      {name:"Henry", email:"henry@hotmail.com"},
      {name:"Coco", email:"coco@gmail.com"}
    ]
  },
  components:{
    test:{
      props:["name","email"],
      template: "<div>{{name}}:{{email}}</div>"
    }
  }
});

render:

<div>Henry:henry@hotmail.com</div>
<div>Coco:coco@gmail.com</div>

但如果一組有好幾欄資料的話props要一個 一個指定超長的,這時候就可以用v-bind

<div id="app">
  <!--<test v-for="text in posts" :name="post.name" :email="text.email"></test>-->
  <test v-for="text in posts" v-bind="text"></test>
</div>

當要把一個物件裡面的屬性全部指定給一個component的話,除了一個一個資料來綁定之外還可以用v-bind="資料屬性",這樣就會直接把所有資料裡的屬性分別指定給component當成他的props,,不用一個一個去指定。


上一篇
27 Vue組件 - props (1)
下一篇
29 Vue組件 - props(3)
系列文
從0開始vue.js的30天學習日誌30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言