案例一:native 綁定的input事件能夠觸發dosomething函數app
<div id="app"> <!-- native 將原生事件綁定到組件 --> <base-input label="姓名" value="Vue" placeholder="請輸入名字" v-on:input.native="dosomething"></base-input> </div> <script> Vue.component('base-input', { inheritAttrs: false, props: ['label', 'value'], template: ` <label> {{ label }} <input v-bind="$attrs" v-bind:value="value" > </label> ` }); new Vue({ el: '#app', methods: { dosomething() { console.log('y'); } } }); </script>
案例二:native 綁定的focus事件卻不能夠觸發dosomething函數(下面案例三爲解決方案)函數
<div id="app"> <!-- native 將原生事件綁定到組件 --> <base-input label="姓名" value="Vue" placeholder="請輸入名字" v-on:focus.native="dosomething"></base-input> </div> <script> Vue.component('base-input', { inheritAttrs: false, props: ['label', 'value'], template: ` <label> {{ label }} <input v-bind="$attrs" v-bind:value="value" > </label> ` }); new Vue({ el: '#app', methods: { dosomething() { console.log('y'); } } }); </script>
案例三:不使用native,使用$listeners(將全部的事件監聽器指向這個組件的某個特定的子元素),能夠觸發dosomething函數this
<div id="app"> <base-input label="姓名" value="Vue" placeholder="請輸入名字" v-on:focus="dosomething"></base-input> </div> <script> Vue.component('base-input', { inheritAttrs: false, props: ['label', 'value'], template: ` <label> {{ label }} <input v-bind="$attrs" v-bind:value="value" v-on="$listeners" > </label> ` }); new Vue({ el: '#app', methods: { dosomething() { console.log('y'); } } }); </script>
案例四:從新定義$listeners,覆蓋原有監聽行爲code
<div id="app"> <base-input label="姓名" value="Vue" placeholder="請輸入名字" v-on:focus="dosomething"></base-input> </div> <script> Vue.component('base-input', { inheritAttrs: false, props: ['label', 'value'], computed: { listeners: function() { var vm = this // `Object.assign` 將全部的對象合併爲一個新對象 return Object.assign({}, // 咱們從父級添加全部的監聽器 this.$listeners, // 而後咱們添加自定義監聽器, // 或覆寫一些監聽器的行爲 { focus: function (event) { console.log('z'); } } ) } }, template: ` <label> {{ label }} <input v-bind="$attrs" v-bind:value="value" v-on="listeners" > </label> ` }); new Vue({ el: '#app', methods: { dosomething() { console.log('y'); } } }); </script>
總結:一切都是爲了支持組件自定義原生事件component