1. 程式人生 > >Vue.js元件

Vue.js元件

Vue.js元件

  • 所有元件需要在初始化根例項前註冊
    // 註冊
    Vue.component('my-component', {
      template: '<div>A custom component!</div>'
    })
    
    // 建立根例項
    new Vue({
      el: '#example'
    })
    
  • 元件作用域
    • 全域性與區域性
    • 全域性元件:
      Vue.component(tagName, options)
      
    • 區域性元件,在一個Vue例項中設定components屬性
      new Vue({
        // ...
        components:
      { // <my-component> 將只在父元件模板中可用 'my-component': Child } })
  • 元件中的data屬性必須是一個function
    Vue.component('simple-counter', {
      template: '<button v-on:click="counter += 1">{{ counter }}</button>',
      // 技術上 data 的確是一個函數了,因此 Vue 不會警告,
      // 但是我們卻給每個元件例項返回了同一個物件的引用
      data: function
    () { return { a:1, b:2 } } })

元件間的資料傳輸

  • 父子元件的關係可以總結為 prop 向下傳遞,事件向上傳遞
  • 父元件通過 prop 給子元件下發資料,子元件通過事件給父元件傳送訊息
    Vue.component('child', {
      // 宣告 props
      props: ['message'],
      // 就像 data 一樣,prop 也可以在模板中使用
      // 同樣也可以在 vm 例項中通過 this.message 來使用
      template: '<span>{{ message }}</span>'
    })
  • 通過為元素傳入props中定義的屬性值來傳資料
    <child message="hello!"></child>
    
  • 子元件與父元件傳資料,通過子元件往父元件觸發事件來傳遞資料
    Vue.component('balance', {
        template: `
        <div>
            <show @show-balance='show_balance'></show> 
            <div v-if='show'>
            顯示餘額:$100,000,000
            </div>
        </div>
        `, // 父元件中的子元件元素中為觸發的show-balance事件觸發方法,傳入方法名 在 觸發的方法中通過形參就可以獲取字元件傳來的資料物件
        data: function () {
            return {
                show: false
            }
        },
        methods: {
            show_balance: function (data) {
                this.show = true
                console.log(data)
            }
        }
    })
    
    Vue.component('show', {
        template: '<button @click="on_click()">顯示餘額</button>', // 點選觸發一個方法,該方法傳送一個show-balance事件到父元件中,
        // 同時傳入資料物件
        methods: {
            on_click: function () {
                this.$emit('show-balance', {
                    a: 1,
                    b: 2
                })
            }
        }
    })
    
    
    var app = new Vue({
        el: '#app',
    })