1. 程式人生 > 實用技巧 >Vue 元件註冊

Vue 元件註冊

全域性元件

全域性元件註冊語法

components中的兩個引數元件名稱和元件內容

Vue.component(元件名稱, {
      data: 元件資料,
      template:元件模板內容
    })

全域性元件註冊應用

元件建立:

Vue.component('button-counter', {
      data: function(){
        return {
          count: 0
        }
      },
      template: '<button @click="handle">點選了{{count}}次</button>',
      methods: {
        handle: 
function(){ this.count ++; } } }) var vm = new Vue({ el: '#app', data: { } });

如何在頁面中運用,直接在頁面中應用元件名稱

<div id="app">
    <button-counter></button-counter>
</div>

這個元件是可以重用的,直接在頁面中多次使用,切資料相互獨立,互不干擾

元件註冊注意事項

  1. data必須是一個函式
    • 分析函式與普通物件的對比
  2. 元件模板內容必須是單個根元素
    • 分析演示實際的效果
  3. 元件模板內容可以是模板字串
    • 模板字串需要瀏覽器提供支援(ES6語法)
  4. 元件命名方式
    • 短橫線方式
Vue.component('my-component',{/*...*/})
    • 駝峰方式
Vue.component('MyComponent',{/*...*/})

如果使用駝峰式命名元件,那麼在使用元件的時候,只能在字串模板中用駝峰的方式使用元件,但是在普通的標籤模板中,必須使用短橫線的方式使用元件

區域性元件

區域性元件只能在註冊它的父元件中使用

區域性元件註冊語法

var ComponentA = {/*
...*/} var ComponentB = {/*...*/} var ComponentC = {/*...*/} new Vue({ el : '#app', components: {     'component-a' : ComponentA,     'component-b' : ComponentB,     'component-c' : ComponentC   } })

元件的建立

    Vue.component('test-com',{
      template: '<div>Test<hello-world></hello-world></div>'
    });
    var HelloWorld = {
      data: function(){
        return {
          msg: 'HelloWorld'
        }
      },
      template: '<div>{{msg}}</div>'
    };
    var HelloTom = {
      data: function(){
        return {
          msg: 'HelloTom'
        }
      },
      template: '<div>{{msg}}</div>'
    };
    var HelloJerry = {
      data: function(){
        return {
          msg: 'HelloJerry'
        }
      },
      template: '<div>{{msg}}</div>'
    };
    var vm = new Vue({
      el: '#app',
      data: {
        
      },
      components: {
        'hello-world': HelloWorld,
        'hello-tom': HelloTom,
        'hello-jerry': HelloJerry
      }
    });

頁面中的應用

<div id="app">
    <hello-world></hello-world>
    <hello-tom></hello-tom>
    <hello-jerry></hello-jerry>
    <test-com></test-com>
  </div>