vue-8-組件
阿新 • • 發佈:2017-09-29
strong 類型 變量 cnblogs incr option 使用 class 字符串
註冊
註冊一個全局組件:Vue.component(tagName, options) Vue.component(‘my-component‘, { template: ‘<div>A custom component!</div>‘ }) <div id="example"> <my-component></my-component> </div> new Vue({ el: ‘#example‘ }) 局部註冊:通過組件實例選項註冊 var Child = { template: ‘<div>A custom component!</div>‘ } new Vue({ el: ‘#example‘, components: {//<my-component> 將只在父模板可用 ‘my-component‘: Child } })
使用is屬性:
<table> <tr is="my-row"></tr> //==<my-row>...</my-row>,table下標簽有HTML的限制可以換用is的形式 </table>
使用模板,這些限制將不適用:
-
<script type="text/x-template">
-
JavaScript 內聯模板字符串
- .vue 組件
data必須是一個函數,並且,如果返回一個公共的變量,實例之間將共享數據。
props://prop 是單向綁定的
<child my-message="hello!"></child>
//當使用的不是字符串模板,camelCased (駝峰式) 命名的 prop 需要轉換為相對應的 kebab-case (短橫線隔開式) 命名:
Vue.component(‘child‘, { props: [‘myMessage‘], template: ‘<span>{{ myMessage }}</span>‘ })
動態prop:<div> <input v-model="parentMsg"> <child :my-message="parentMsg"></child> </div>
props 傳遞所有的屬性,綁定一個對象: todo: { text: ‘Learn Vue‘, isComplete: false } <child v-bind="todo"></child>
<!-- 傳遞實際的 number --> <comp v-bind:some-prop="1"></comp>
props驗證 原生構造器類型: String 、Number、 Boolean、 Function、 Object、 Array、 Symbol type 也可以是一個自定義構造器函數,使用 instanceof 檢測。 Vue.component(‘example‘, { props: { // 基礎類型檢測 (`null` 意思是任何類型都可以) propA: Number, // 多種類型 propB: [String, Number], // 必傳且是字符串 propC: { type: String, required: true }, // 數字,有默認值 propD: { type: Number, default: 100 }, // 數組/對象的默認值應當由一個工廠函數返回 propE: { type: Object, default: function () { return { message: ‘hello‘ } } }, // 自定義驗證函數 propF: { validator: function (value) { return value > 10 } } } })
非prop屬性,也允許加入到屬性,(如一些第三方組件,可以把屬性直接添加到組件上 ,不需要事先定義 prop
)
<bs-date-input data-3d-date-picker="true"></bs-date-input>
從父組件傳來的屬性值,如class會和組件模板定義的同名屬性合並
自定義事件
<div id="counter-event-example"> <p>{{ total }}</p> <button-counter v-on:increment="incrementTotal"></button-counter> //$on用來監聽increment事件 <button-counter v-on:increment="incrementTotal"></button-counter> </div> //子組件: Vue.component(‘button-counter‘, { template: ‘<button v-on:click="incrementCounter">{{ counter }}</button>‘, data: function () { return { counter: 0 } }, methods: { incrementCounter: function () { this.counter += 1 this.$emit(‘increment‘) //$emit用來觸發increment事件,調用incrementTotal方法 } }, })
new Vue({ el: ‘#counter-event-example‘, data: { total: 0 }, methods: { incrementTotal: function () { this.total += 1 } } })
vue-8-組件