自定義事件也能夠用來建立自定義的表單輸入組件,使用 v-model來進行數據雙向綁定。牢記:ide
<input v-model="something">
僅僅是一個語法糖:this
<input v-bind:value="something" v-on:input="something = $event.target.value">
因此在組件中使用時,它至關於下面的簡寫:spa
<input v-bind:value="something" v-on:input="something = arguments[0]">
因此要讓組件的 v-model 生效,它必須:雙向綁定
一個很是簡單的貨幣輸入:
HTML代碼:component
<currency-input v-model="price"></currency-input>
JS代碼:orm
Vue.component('currency-input', { template: '\ <span>\ $\ <input\ ref="input"\ v-bind:value="value"\ v-on:input="updateValue($event.target.value)"\ >\ </span>\ ', props: ['value'], methods: { // Instead of updating the value directly, this // method is used to format and place constraints // on the input's value updateValue: function (value) { var formattedValue = value // Remove whitespace on either side .trim() // Shorten to 2 decimal places .slice(0, value.indexOf('.') + 3) // If the value was not already normalized, // manually override it to conform if (formattedValue !== value) { this.$refs.input.value = formattedValue } // Emit the number value through the input event this.$emit('input', Number(formattedValue)) } } })