標籤:ops 位置 this 學習筆記 ext 例子 function text 選項
一、組件的註冊
組件的註冊分為全域註冊和局部註冊
全域註冊
1 Vue.component(‘my-component‘, {2 // 選項3 })
局部註冊
1 var Child = { 2 template: ‘<div>A custom component!</div>‘ 3 } 4 new Vue({ 5 // ... 6 components: { 7 // <my-component> 將只在父模板可用 8 ‘my-component‘: Child 9 }10 })
二、使用Props傳遞資料
組件執行個體的範圍是孤立的。這意味著不能並且不應該在子組件的模板內直接引用父組件的資料。可以使用 props 把資料傳給子組件。
在組件中需要顯式的用props選項來聲明:
1 Vue.component(‘child‘, {2 // 聲明 props3 props: [‘message‘],4 // 就像 data 一樣,prop 可以用在模板內5 // 同樣也可以在 vm 執行個體中像 “this.message” 這樣使用6 template: ‘<span>{{ message }}</span>‘7 })
在HTML傳入一般字元串中:
1 <child message="hello!"></child>
也可以動態地綁定props,使用 v-bind 動態綁定表單值,HTML如下:
1 <div>2 <input v-model="parentMsg">3 <br>4 <child v-bind:my-message="parentMsg"></child>5 </div>
三、傳遞資料
- 使用 $on(eventName) 監聽事件
-
使用 $emit(eventName) 觸發事件
父組件可以在使用子組件的地方直接用 v-on 來監聽子組件觸發的事件。
下面是一個例子:
//HTML<div id="counter-event-example"> <p>{{ total }}</p> <button-counter v-on:increment="incrementTotal"></button-counter> <button-counter v-on:increment="incrementTotal"></button-counter></div>//JsVue.component(‘button-counter‘, { template: ‘<button v-on:click="increment">{{ counter }}</button>‘, data: function () { return { counter: 0 } }, methods: { increment: function () { this.counter += 1 this.$emit(‘increment‘) } },})new Vue({ el: ‘#counter-event-example‘, data: { total: 0 }, methods: { incrementTotal: function () { this.total += 1 } }})
四、使用slot分發內容
除非子組件模板包含至少一個 <slot> 插口,否則父組件的內容將會被丟棄。當子組件模板只有一個沒有屬性的 slot 時,父組件整個內容片段將插入到 slot 所在的 DOM 位置,並替換掉 slot 標籤本身。
最初在 <slot> 標籤中的任何內容都被視為備用內容。備用內容在子組件的範圍內編譯,並且只有在宿主要元素為空白,且沒有要插入的內容時才顯示備用內容。
假定 my-component 組件有下面模板:
<div> <h2>I‘m the child title</h2> <slot> 如果沒有分發內容則顯示我。 </slot></div>
父組件模版:
<div> <h1>I‘m the parent title</h1> <my-component> <p>This is some original content</p> <p>This is some more original content</p> </my-component></div>
渲染結果:
<div> <h1>I‘m the parent title</h1> <div> <h2>I‘m the child title</h2> <p>This is some original content</p> <p>This is some more original content</p> </div></div>
五、可複用組件
在編寫組件時,記住是否要複用組件有好處。一次性組件跟其它組件緊密耦合沒關係,但是可複用組件應當定義一個清晰的公開介面。
Vue 組件的 API 來自三部分 - props, events 和 slots :
1 <my-component2 :foo="baz"3 :bar="qux"4 @event-a="doThis"5 @event-b="doThat"6 >7 <img slot="icon" src="...">8 <p slot="main-text">Hello!</p>9 </my-component>
六、子組件索引
儘管有 props 和 events ,但是有時仍然需要在 JavaScript 中直接存取子組件。為此可以使用 ref 為子組件指定一個索引 ID 。例如:
1 <div id="parent">2 <user-profile ref="profile"></user-profile>3 </div>
1 var parent = new Vue({ el: ‘#parent‘ })2 // 訪問子組件3 var child = parent.$refs.profile
【學習筆記】Vue.js組件