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>

 

Tags: