標籤:ack 分享 元素 全域 先來 編譯 需要 custom 生效
組件(Component)是 Vue.js 最強大的功能之一。組件可以擴充 HTML 元素,封裝可重用的代碼。在較高層面上,組件是自訂元素, Vue.js 的編譯器為它添加特殊功能。
組件的使用有三個步驟:
1、建立組件構造器
2、註冊組件
3、使用組件
先來看一段代碼:
<!DOCTYPE html><html> <body> <div id="app"> <!-- 3. #app是Vue執行個體掛載的元素,應該在掛載元素範圍內使用組件--> <my-component></my-component> </div> </body> <script src="js/vue.js"></script> <script> // 1.建立一個組件構造器 var myComponent = Vue.extend({ template: ‘<div>我是一個div,我是在組件構造器中建立的</div>‘ }) // 2.註冊組件,並指定組件的標籤,組件的HTML標籤為<my-component> Vue.component(‘my-component‘, myComponent)
// 3.使用組件,組件應該掛載到某個Vue執行個體下,否則它不會生效。 new Vue({ el: ‘#app‘ }); </script></html>
訪問以下就會發現 :我們自訂的組件 <my-component>已經換成了我們的組件構造器中的內容了
理解組件的建立和註冊:
1、Vue.extend()是Vue構造器的擴充,調用Vue.extend()建立的是一個組件構造器,而不是一個具體的組件執行個體
2、Vue.extend()構造器有一個選項對象,選項對象的template屬性用於定義組件要旋繞的HTML
3、使用Vue.component()註冊組件時,需要提供兩個參數,第一個是組件的標籤名,第二個是組件構造器
4、Vue.component()方法內部會調用組件構造器,建立一個組件執行個體
5、組件應該掛載到某個Vue執行個體下,否則不會生效。
全域註冊和局部註冊
調用Vue.component()註冊組件時,組件的註冊是全域的,這意味著該組件可以在任意Vue樣本下使用。
如果不需要全域註冊,或者是讓組件使用在其它組件內,可以用選項對象的components屬性實現局部註冊。
上面的樣本可以改為局部註冊的方式:
<!DOCTYPE html><html> <body> <div id="app"> <!-- 3. my-component只能在#app下使用--> <my-component></my-component> </div> </body> <script src="js/vue.js"></script> <script> // 1.建立一個組件構造器 var myComponent = Vue.extend({ template: ‘<div>This is my first component!</div>‘ }) new Vue({ el: ‘#app‘, components: { // 2. 將myComponent組件註冊到Vue執行個體下 ‘my-component‘ : myComponent } }); </script></html>
由於my-component組件是註冊在#app元素對應的Vue執行個體下的,所以它不能在其它Vue執行個體下使用
<div id="app2"> <!-- 不能使用my-component組件,因為my-component是一個局部組件,它屬於#app--> <my-component></my-component></div><script> new Vue({ el: ‘#app2‘ });</script>
如果你這樣做了,瀏覽器會提示一個錯誤:
可以看出:" Unknown custom element: <my-component> - did you register the component correctly?"
標明組件沒有被建立成功,不能調用此組件,也就是說局部組件只能用在其註冊的元素掛載下
總結:
全域群組件用到的是 Vue.component(tagName,option)
局部組件用到的是components:{tagName:option},tagname是自訂的組件名稱,option是組件構造器
/註冊組件(全域 component)Vue.component("my-component",{ template:‘<div>這是一個全域群組件測試 </div>‘});new Vue({ el:"#app5"})//(局部components)new Vue({ el:"#app6", components:{ ‘test-component‘:{ template:"<div>這是一個局部的組件測試</div>" } }});
vue.js中的全域群組件和局部組件