iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 16
0
Modern Web

菜菜菜的 Vue 30天系列 第 16

components

菜菜菜的 Vue 30天 - Day16

component

我覺得在 Vue 裡 component 是一個非常重要的一個部分,使用 component 能夠將網頁的內容封裝起來,提高程式碼複用性。

可以想像一下很久以前的網頁建立必須每一頁都是獨立的檔案,甚至每一支獨立的檔案內都有很多重複性很高的元素及內容,現在有了 SPA 的框架就能夠使用一個個的 component 組建成完整的網頁。

概念如下:

註冊

那 component 註冊的部份同樣也是分為 全域區域 2 種。

  1. 全域

全域的部分我們一樣直接使用 Vue 實例來做註冊

Vue.component('button-add-count', {
  data: function () {         //component 內一樣能夠使用 data、methods 以及後面會介紹的 lifecycle
    return {
      count: 0
    }
  },
  template: '<button @click="count++">Clicked {{ count }} times.</button>'     //component 內所要使用的 DOM
})
  1. 區域

區域的部分是能夠直接在 Vue 實例內使用 components 來做註冊

<script>
  const vm = new Vue({
    el: '#app',
    components: {
      data: function() {
        return {
          count: 0
        }
      },
      'button-add-count': {
        template: '<button @click="count++">Clicked {{ count }} times.</button>'
      }
    }
  })
</script>

使用

上面介紹了如何去註冊 component,接下來就是如何去使用了。

其實使用方式很簡單,我們只要註冊了 component 之後呢就可以像添加 HTML Tags 一樣的直接新增 component。

<body>
  <div id="app">
    <button-add-count></button-add-count>
  </div>
</body>

這樣子它渲染出來的還是一個 button,甚至我們就能開始重複使用它

<body>
  <div id="app">
    <button-add-count></button-add-count>
    <button-add-count></button-add-count>
    <button-add-count></button-add-count>
  </div>
</body>

注意

這邊有一點要特別注意!!

我們註冊了一個 component 裡面如果使用到了 data 必須使用 function(){} 的格式,在官網有提到,使用 function(){} 的方式才不會影響到其他同樣 component 內的 data,如果使用 object 格式的話會早成其他同樣 component 一併被修改到。

我下面來看一下官方的範例

  1. function(){}

  1. object

到這邊可能有人會想到上面有提到每個 component 裡面都擁有自己的 data,那我想要把這個 component 裡的資料傳給其他的頁面或 component 使用那該怎麼傳呢?!

這部分我們會在後面幾章介紹囉~


上一篇
filter
下一篇
props
系列文
菜菜菜的 Vue 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言