Vue中三种定义组件的方式

1,226 阅读1分钟

下面的代码示例中使用的是Vue的完整版。

第一种定义方式:建立一个以.vue后缀的文件,然后导入得到一个对象,将该对象定义到vue实例的components中:

import Demo from './Demo.vue'  //导入Demo.vue文件
const Vue = window.Vue

new Vue({
  el: '#app',
  components: {
    Demo: Demo       //在ES6语法中可直接简写为Demo
  },
  data() {
    return {
      n: 0
    }
  },
  methods: {
    add() {
      this.n += 1
    }
  },
  template: `
  <div>
  {{n}}
  <button @click="add">+1</button>
  <Demo/>  //使用组件
</div>
  `
})

第二种定义方式:直接使用Vue.component()定义

const Vue = window.Vue

Vue.component('Demo', {          //定义组件,{}中的内容其实和创建vue实例时new Vue()中的内容一样
  template: `<div>demo111</div>`
});

new Vue({
  el: '#app',

  data() {
    return {
      n: 0
    }
  },
  methods: {
    add() {
      this.n += 1
    }
  },
  template: `
  <div>
  {{n}}
  <button @click="add">+1</button>
  <Demo/>    //使用组件
</div>
  `
})

第三种方式:其实是上面两种方式的结合

const Vue = window.Vue

new Vue({
  el: '#app',
  components: {
    Demo: {
      template: `<div>demo222</div>`  //定义组件
    }
  },
  data() {
    return {
      n: 0
    }
  },
  methods: {
    add() {
      this.n += 1
    }
  },
  template: `
  <div>
  {{n}}
  <button @click="add">+1</button>
  <Demo/>   //使用组件
</div>
  `
})

组件名一般要首字母大写,避免使用的时候与一般的html标签发生混淆。