Prop 验证
組件可以為 props 指定驗證要求。
prop 是一個對象而不是字符串數組時,它包含驗證要求:
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}}} })type 可以是下面原生構造器:
- String
- Number
- Boolean
- Function
- Object
- Array
type 也可以是一個自定義構造器,使用 instanceof 檢測。
自定義事件
父組件是使用 props 傳遞數據給子組件,但如果子組件要把數據傳遞回去,就需要使用自定義事件!
我們可以使用 v-on 綁定自定義事件, 每個 Vue 實例都實現了事件接口(Events interface),即:
- 使用 $on(eventName) 監聽事件
- 使用 $emit(eventName) 觸發事件
另外,父組件可以在使用子組件的地方直接用 v-on 來監聽子組件觸發的事件。
以下實例中子組件已經和它外部完全解耦了。它所做的只是觸發一個父組件關心的內部事件。
<!DOCTYPE html> <html><head><meta charset="UTF-8"><title>自定義事件</title><script src="js/vue.js"></script></head><body><div id="app"><div id="counter-event-example"><p>{{total}}</p><button-counter v-on:click.native="incrementTotal"></button-counter><button-counter v-on:increment="incrementTotal"></button-counter></div></div><script>Vue.component('button-counter',{template:'<button v-on:click="incrementHandler">{{counter}}</button>',data:function(){return{counter:0}},methods:{incrementHandler:function(){this.counter+=1this.$emit('increment')}}})new Vue({el:'#counter-event-example',data:{total:0},methods:{incrementTotal:function(){this.total+=1}}})</script></body> </html>?
總結
- 上一篇: props属性
- 下一篇: VUE data传值