什么是組件?
組件 (Component) 是 Vue.js 最強大的功能之一。組件可以擴展 HTML 元素,封裝可重用的代碼。在較高層面上,組件是自定義元素,Vue.js 的編譯器為它添加特殊功能。在有些情況下,組件也可以是原生 HTML 元素的形式,以 is 特性擴展。
我知道vue中核心就是組件,但是組件是什么呢?組件有什么用呢?
這里來說說怎么用組件?怎么樣創(chuàng)建自己的組件?:
1)創(chuàng)建自己的組件
通過vue.extend("template");通過vue構造器去拓展一個模板,然后注冊,最后使用。
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>進一步了解component的話法糖</title> <script src="../vue.js"></script> </head> <body> <div>這是一個全局注冊的</div> <div id="app"> <parent></parent> </div> </body></html><script> var child= Vue.extend({template:'<p>this is child component</p>'}); //Vue.component("組件名",{});在注冊之前會自動創(chuàng)建(調用vue.extend()方法 ) //這是一個全局注冊(兼創(chuàng)建與注冊) Vue.component("parent",{//有時候我們可以省略,extend. template:'<div>this is parent component ------ {{text}} <child-component></child-component> </div>',//局部使用 components:{ "child-component":child,//局部注冊 }, //data:function(){} data(){ return {text:'哈哈哈,我是組件內部的text'} }, }); var vm= new Vue({ el:'#app', data:{}, });進階一下:(組件內部在套組件,(components下面的components))
通過下面的例子,我就想說明一點,組件是vue構造器的拓展,所以組件可能擁有構造器的幾乎所有屬性(在寫這篇博客前,我們沒有聽到這個說法,所以可能是錯的,不要信)
<body> <div>這是一個局部注冊</div> <div id="app1"> <div><button v-on:click=get>這里觸發(fā)get方法</button></div> <parent-components></parent-components> </div></body> <script> // var child=Vue.extend({template:"<span> ------child element------</span>"}); var vp=new Vue({ el:'#app1', data:{}, methods:{ get:function(){alert("這是構造器中get(全局)");} }, components:{ "parent-components":{ template:"<div>---------<span> parent components</span><p><button v-on:click=get>點擊觸發(fā)parent的get</button></p> <div><child-component></child-component></div>--------</div>", components:{ //局部注冊再一次局部注冊 "child-component":{ template:"<span> ------child <button v-on:click=get>點擊觸發(fā)child中的get方法</button>element------</span>", methods:{ get:function(){ alert("這是局部注冊child-component組件中get"); } } } }, methods:{ get:function(){ alert("這是蟬聯(lián)注冊parent-components里面的方法"); } }, }, }, });</script>
新聞熱點
疑難解答
圖片精選