d2.1.2 組件使用在 input 上監聽原生事件
by BDeer
HTML
<div id="app">
<base-input></base-input>
</div>
<script>
Vue.component('base-input',{
inheritAtter:false,
prop:['label','value'],
computed:{
inputListeners: function(){
var vm = this
// `Object.assign` 将所有的对象合并为一个新对象
return Object.assign({},
//我們從父級添加所有監聽器
this.$listeners,
//然後我們添加自訂監聽器,
//或覆蓋一些監聽器的行為
{
// 這裡確保組件配合 `v-model` 的工作
input: function (event) {
vm.$emit('input', event.target.value)
}
})
}
},
template: `
<label>
{{ label }}
<input
v-bind="$attrs"
v-bind:value="value"
v-on="inputListeners"
>
</label>
`
})
</script>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
Vue
let onVm = new Vue({
el:'#app'
})