vue-创建组件的5种方法

Vue组件分为全局组件和局部组件以及Vue 构造器创建组件,统计为5种创建组件的方式

一、效果截图

创建的h1-h5五个组件

组件名称和结构

二、具体的写法如下:

1、全局-直接创建

Vue.component('first', {
    template: '<h1>第一种创建组件的方法</h1>'
})

2、全局-定义再创建

const second = {
    template: '<h2>第二种创建组件的方法</h2>'
}
Vue.component('second', second);

3、局部注册组件

new Vue({
    el: '#app',
    components: {
        third: {
           'template': '<h3>第三种创建组件的方法</h3>'
        }
    }
})

4、在html中定义模板,由id引入到组件,代码有高亮

// html种写模板
<template id="fourth">
    <h4>第四种创建组件的方法</h4>
</template>
// 组件通过id导入
Vue.component('fourth', {
    template: '#fourth'
})

5、使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象

//定义挂载的dom
<div id="sixth"></div>
// 创建Vue.extend构造器
var sixth = Vue.extend({
    template: '<h5>第五种创建组件的方法</h5>'
})
// 创建 Profile 实例,并挂载到一个元素上。
new sixth().$mount('#sixth')

猜你喜欢

转载自www.cnblogs.com/piaoyi1997/p/13387340.html