iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 6
0
Data Technology

讓你資料美美的(d3.js+vue.js)系列 第 6

繼續介紹Vue的component

Component

延續前一天的內容

html

#root
  h1 {{title}}
  h2 {{subtitle}}
  viwer    

js(Local Registration)

var viwer=Vue.component('viwer',{
  template: `
    <div>
      <button @click="view" > show datas</button>
      <button @click="hide" > hide datas</button>
      <ul>
        <li v-for="fruit in this.fruits"
             v-if="fruit.show" 
             v-bind:style="{color:fruit.color}"
        >{{fruit.fruit}}
        </li>
      </ul>
      
    </div>
        
  `,
  data() {
    return{
      fruits:[]
    }
  },
  methods:{
    view() {
      this.fruits = datas;
    },
    hide() {
      this.fruits = [];
    }
  },
});

var vm = new Vue({
  el: "#root",
  data: {
    title: "讓資料美美的#5",
    subtitle: "這次將介紹component",
  },
  
  components: {
    viwer,
  },

});

js(Global Registration)

Vue.component('viwer',{
  template: `
    <div>
      <button @click="view" > show datas</button>
      <button @click="hide" > hide datas</button>
      <ul>
        <li v-for="fruit in this.fruits"
             v-if="fruit.show" 
             v-bind:style="{color:fruit.color}"
        >{{fruit.fruit}}
        </li>
      </ul>
      
    </div>
        
  `,
  data() {
    return{
      fruits:[]
    }
  },
  methods:{
    view() {
      this.fruits = datas;
    },
    hide() {
      this.fruits = [];
    }
  },
});

var vm = new Vue({
  el: "#root",
  data: {
    title: "讓資料美美的#6",
    subtitle: "這次將介紹component",
  },
});

Vue.component('定義component的名稱',{
  template: `   
      定義 component的內容 單行的話可以使用"code...",多行則要使用`code...`
  `,
  data() {
      component中的data需要定義成一個function這是比較需要特別注意的
  },
  methods:{
      其他的用法則大致相同
  },
});

可以發現Global Registration 跟 Local Registration 在定義時的差別其實不多

在定義Local Registration 時需要賦予它一個名稱,好處是可以不用將每個變數都註冊到全域中,當然還是看使用的情況

Vue.component('viwer',{ ... Global Registration
var viwer=Vue.component('viwer',{... Local Registration

另外Local Registration 定義完後要呼叫前須先在vm中加入components並且將自己定義的名稱加入
Global Registration則不需要

var vm = new Vue({
  el: "#root",
  data: {
    title: "讓資料美美的#5",
    subtitle: "這次將介紹component",
  },
  
  components: {
    viwer,
  },

});

前一日提到 component 是reuseble

所以可以在不同的地方重複呼叫Conponent
https://ithelp.ithome.com.tw/upload/images/20171225/20105602Pua6jPcz6F.png

定義Component時需要注意的細節

  • data的定義方法為 data() {} 而不是 data:{} 之所以要定義成function的原因是為了避免當有重複使用component時data不會全部一次被改變,而是依照個別執行的狀況,詳情可以參考官方的文件

  • DOM模板

当使用 DOM 作为模板时 (例如,使用 el 选项来把 Vue 实例挂载到一个已有内容的元素上),你会受到 HTML 本身的一些限制,因为 Vue 只有在浏览器解析、规范化模板之后才能获取其内容。尤其要注意,像 、、、 这样的元素里允许包含的元素有限制,而另一些像 这样的元素只能出现在某些特定元素的内部。
這是來自官方文件的說明,要克服這些限制可以使用 is 屬性,或是使用官方推薦的 string template ,有興趣可以參考官方文件。

本次程式碼https://codepen.io/FanWay/pen/wpoyGw


上一篇
簡單介紹vue中的component
下一篇
Vue的prop
系列文
讓你資料美美的(d3.js+vue.js)30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言