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')