iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 14
0
自我挑戰組

vue.js 30天學習軌跡系列 第 14

Day14 vue.js - 組件(Components)介紹及建立

組件(Components)是可重用的代碼塊,可以同時具有結構和功能。
它們有助於創建更加模塊化和可維護的代碼庫。

官方圖式

每個components可能會有HenderSidecontent等組件,每個components又包含了其它的像導覽列、文章之類的components,通常一個應用會以一棵嵌套的組件樹的形式來組織。


如何使用?

  • 全域註冊(Registration)
  • 局部註冊(Local Registration)

/images/emoticon/emoticon31.gif

全域註冊(Registration)

可以用在任 new Vue 的模板中

<div id="app">
  <my-component-name></my-component-name>  
</div>

下圖中的 my-component-name 是 自訂的 components的名子

Vue.component('my-component-name',{ 
  template: '<div><p>{{mesg}}</p><button @click="date">按我看看時間</button></div>',
  data(){
    return {
      mesg:'現在幾點呢?'
    }
  },
  methods:{
    date(){
      alert(new Date())
    }
  }
})

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

局部註冊(Local Registration)

JavaScript 對象來定義組件
然後在 components 選項中定義你想要使用的組件

var child ={
  template: '<div><p>{{mesg}}</p><button @click="date">按我看看時間</button></div>',
  data(){
    return {
      mesg:'現在幾點呢?'
    }
  },
  methods:{
    date(){
      alert(new Date())
    }
  }
}
new Vue({ 
  el: '#app' ,
  components : {
    'my-component-name': child
  }
})

引入template 個兩種方法

  • 字串 模版 (String Template)

  • DOM 模版 (DOM Template)

字串 模版 (String Template)

如圖 就是直接把字串塞入 Template
但是這樣就會使程式碼有點難閱讀

DOM 模版 (DOM Template)

將模板被定義在例如 html 文件中的 <script> 標籤裡
<script> 標籤使用 <text/x-template 標記>,並由組件定義的 id 引用

<div id="app">
  <table  class="table">
     <thead>
    </thead>
    <tbody> 
      <tr is="my-component" v-for="(item,id) in foods" :food="item" :key="id"></tr>
    </tbody>
  </table> 
</div>

<script type="text/x-template" id="myComponent">
  <tr>
    <th></th>
    <th>{{food.name}}</th>
    <th>{{food.price}}</th>
  </tr>
</script>
Vue.component('my-component', { 
  template: '#myComponent',  
  props :['food']
})
new Vue({ 
  el: '#app' ,
  data:{
    foods:[
        {
          name : '薯條',
          price: 20,
        },
        {
          name: '甜不辣',
          price : 20,
        },
        {
          name: '雞排',
          price : 55
        }
      ]
  }
})

小提示

上面範例中有使用 :is 來動態綁定渲染的模版,
is屬性可解決在特定 HTML 標籤包含格式下的問題,
例如像是<ul>、<ol>、<table>、<select> 這樣的元素裡允許包含的元素有限制而非客製化標籤。

/images/emoticon/emoticon08.gif


上一篇
Day13 vue.js - 生命週期
下一篇
Day15 vue.js - 組件(Components)必須使用function return
系列文
vue.js 30天學習軌跡30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

我要留言

立即登入留言