vue全局組件和局部組件
Vue.js的組件化思想 —— 上
一拉庶、Vue中的組件
- Vue視圖層的靈魂 —— 組件化
組件(Component)是 Vue.js 最強大的功能之一。
組件可以擴展 HTML 元素秃励,封裝可重用的代碼氏仗。
在較高層面上,組件是自定義元素夺鲜, Vue.js 的編譯器為它添加特殊功能皆尔。在有些情況下,組件也可以是原生 HTML 元素的形式币励,以 is 特性擴展慷蠕。
- 全局組件的創(chuàng)建和注冊
-
案例代碼:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> <my-component></my-component> </div> <script src="js/vue.js"></script> <script> // 1. 創(chuàng)建組件構造器 var Profile = Vue.extend({ template: '<h1>我是自定義組件</h1>' }); // 2. 注冊組件, 指定組件的名稱 Vue.component('my-component', Profile); new Vue({ el: '#app' }) </script> </body> </html>
調用Vue.extend()創(chuàng)建的是一個組件構造器流炕,構造器有一個選項對象仅胞,選項對象的template屬性用于定義組件要渲染的HTML饼问;
調用Vue.component()注冊組件時揭斧,需要提供2個參數(shù):組件的標簽名 和 組件構造器讹开;注冊的組件要掛載到某個Vue實例下,否則它不會生效闹击;
Vue.extend() 和 Vue.component():由于 Vue 本身是一個構造函數(shù)赏半,Vue.extend() 是一個類繼承方法淆两,它用來創(chuàng)建一個 Vue 的子類并返回其構造函數(shù)秋冰。
而Vue.component() 的作用在于:建立指定的構造函數(shù)與 ID 字符串間的關系,從而讓 Vue.js 能在模板中使用它埃撵;直接向 Vue.component() 傳遞 options 時,它會在內部調用 Vue.extend()暂刘。
- 局部組件的創(chuàng)建和注冊
-
案例代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注冊局部組件</title> </head> <body> <div id="root"> <my-component></my-component> </div> <div id="root2"> <my-component></my-component> </div> <script src="js/vue.js"></script> <script> // 1. 創(chuàng)建組件構造器 var Profile = Vue.extend({ template: '<li>創(chuàng)建局部組件!</li>' }) new Vue({ el: '#root', components: { 'my-component': Profile } }) new Vue({ el: '#root2' }) </script> </body> </html>
-
- 另一種組件創(chuàng)建和注冊方式
-
直接通過Vue.component注冊或獲取全局組件谣拣,主要體現(xiàn)在以下幾種方式:
// 注冊組件,傳入一個擴展過的構造器 Vue.component('my-component', Vue.extend({ /* ... */ })) // 注冊組件绪商,傳入一個選項對象(自動調用 Vue.extend) Vue.component('my-component', { /* ... */ }) // 獲取注冊的組件(始終返回構造器) var MyComponent = Vue.component('my-component')
-
自定義全局組件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> <my-component></my-component> </div> <script src="js/vue.js"></script> <script> Vue.component('my-component', { template: '<h1>自定義全局組件</h1>' }) new Vue({ el:'#app' }) </script> </body> </html>
-
自定義局部組件
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="app"> <my-component1></my-component1> <my-component2></my-component2> </div> <script src="js/vue.js"></script> <script> var app = new Vue({ el: '#app', components: { 'my-component1': { template: '<h1>局部組件1!</h1>' }, 'my-component2': { template: '<h2>局部組件2!</h2>' } } }) </script> </body> </html>
-