vue之組件基礎
阿新 • • 發佈:2019-03-25
code 沒有 以及 eth 相同 start 必須 次數 div
(1)基本示例
Vue組件示例
/* 先註冊組件,定義一個名為button-component的新組件 */ Vue.component(‘button-component‘,{ data:function(){ return { count:0 } }, template:‘<button v-on:click="count++">您點擊了{{count}}次</button>‘ })
組件是可復用的 Vue 實例,且帶有一個名字:在這個例子中是 <button-counter>
。我們可以在一個通過 new Vue
創建的 Vue 根實例中,把這個組件作為自定義元素來使用:
<div id="component_area"> <button-component></button-component> </div>
/* 再實例化,構建組件模板 */ var component_area = new Vue({ el:"#component_area" });
因為組件是可復用的 Vue 實例,所以它們與 new Vue
接收相同的選項,例如 data
、computed
、watch
、methods
以及生命周期鉤子等。僅有的例外是像 el
這樣根實例特有的選項。
(2)組件的復用
可以將組件進行任意次數的復用:
<div id="component_area"> <button-component></button-component> <button-component></button-component> <button-component></button-component> <button-component></button-component> </div>
註意:①當點擊按鈕時,每個組件都會各自獨立維護它的 count
。因為每用一次組件,就會有一個新實例被創建。
②data必須是一個函數
當我們定義這個 <button-counter>
組件時,你可能會發現它的 data
並不是像這樣直接提供一個對象:
data: {
count: 0
}
取而代之的是,一個組件的 data
選項必須是一個函數,因此每個實例可以維護一份被返回對象的獨立的拷貝:
data: function () {
return {
count: 0
}
}
如果 Vue 沒有這條規則,點擊一個按鈕就可能會像如下代碼一樣影響到其它所有實例。如下所示
var start_count = {count:0}; /* 先註冊組件,定義一個名為button-component的新組件 */ Vue.component(‘button-component‘,{ data:function(){ return start_count; }, template:‘<button v-on:click="count++">您點擊了{{count}}次</button>‘ })
(3)組件的組織
.
vue之組件基礎