iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 27
0
自我挑戰組

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

27 Vue組件 - props (1)

Vue組件會使用到上層傳來的props,而props屬性是一個陣列裡面包字串,是用來宣告component使用的props:

Vue實例使用HTML模板來輸出組件,包含了messagehello的字串:

<div id="app">
  <my-component message1='hello' message2='World'></my-component>
</div>

要把Vue實例的資料傳到component裡,使用字串來宣告裡面會用到多少的props,這邊有兩個props:message1message2

Vue.component('my-component',{
  props:['message1','message2']
  template:`
<h1>{{message}}{{test}}</h1>
`
});

new Vue({
  el:'#app'
});

輸出結果:

<div id="app">
  <h1>helloWorld</h1>
</div>

props的命名
Vue組件命名方式有三種,如果關鍵字是 my first component的話,這三種的寫法如下

  • kebab-case(串燒):my-first-component
  • camelCase(駝峰):myFirstComponent
  • PascaleCase:MyFirstComponent

props與組件命名方式一樣,如果component是使用HTML模板的話,因為瀏覽器解析的問題不能使用camelCase,要使用kebab-case寫法,如果是在Vue實例使用字串模板就沒有這個限制,用上面的例子來作範例:

使用HTML模板:

<div id="app">
  <!--錯誤-->
  <!--<my-component messageOne='hello' messageTwo='World'></my-component>-->
  <!--正確-->
  <my-component message-one='hello' message-two='World'></my-component>
</div>

<script>
Vue.component('my-component',{
  props:['messageOne','messageTwo']
  template:`
<h1>{{message}}{{test}}</h1>
`
});
  
new Vue({
  el:'#app'
})
</script>

使用字串模板就可以正常使用camelCasePascaleCase

<div id="app"></div>

<script>
Vue.component('my-component',{
  props:['messageOne','messageTwo']
  template:`
<h1>{{message}}{{test}}</h1>
`
});
  
  new Vue({
    el:'#app',
    template:`
<my-component messageOne='hello' MessageTwo='World'></my-component>
`
  });
</script>

上一篇
26 Vue組件 - 組件資料傳遞、組件結合
下一篇
28 Vue組件 - props(2)
系列文
從0開始vue.js的30天學習日誌30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

1
obxyann
iT邦新手 5 級 ‧ 2019-10-21 11:43:23
<h1>{{message}}{{test}}</h1>
應為
<h1>{{message1}}{{message2}}</h1>
第二例為
<h1>{{messageOne}}{{messageTwo}}</h1>

其次

props: ...,  // ',' 不打會出錯 SyntaxError: missing } after property list
template: ...

謝謝作者的學習筆記~

我就想說怪怪的!!打算要測試一下
沒想到你 已經糾正了

我要留言

立即登入留言