我们知道:组件内的v-model 是 :value="v"和@input="v=$event.target.value"的语法糖;组件上的 v-model 是 :value="v" 和 @input="v=$event"的语法糖,如果我们不想用 value 作为 prop,不想用 input 作为事件,如::valuee="v"和@changee="v=$event",那么应该怎么做呢?只需要在子组件中使用model选项就可以了。代码如下:
html
<div id="app">
<!-- 原本应该将prop和事件监听分开写: -->
<!-- 这里的 $event 用于接收 f-input 内抛出的 $event.target.value -->
<f-input :valuee="fValue" @changee="fValue = $event"></f-input>
<!-- 在子组件内使用 model 选项配置了自定义prop和事件, 因此可以使用 v-model 语法糖-->
<f-input v-model="fValue"></f-input>
<div>{{fValue}}</div>
</div>
js
Vue.component('f-input', {
// 用于自定义 prop和 event, 在父组件中使用 f-input 组件时, 可以使用 v-model 语法糖
model: {
prop: 'valuee',
event: 'changee'
},
props: {
valuee: ''
},
template: `
<div>
<input type="text" :value="valuee" @input="changeValue"
placeholder="f-input" />
{{valuee}}
</div>
`,
// 也可以这样写:
// template: `
// <div>
// <input type="text" :value="valuee" @input="$emit('changee', $event.target.value)"
// placeholder="f-input" />
// {{valuee}}
// </div>
// `,
methods: {
// e默认接受 input 事件触发时的事件对象
changeValue(e) {
this.$emit('changee', e.target.value) // 通过 changee 事件抛出新值
}
}
})
let app = new Vue({
el: '#app',
data() {
return {
fValue: ''
}
}
})