input
// html
<div id="app">
<test-input v-model="num"></test-input>
{{num}}
</div>
// js
let testInput = {
// 子组件内容
template: `
<input type="text" :value="value" @input="$emit('input',$event.target.value)">
`, // *
props: ['value'] // *
}
const app = new Vue({
el: '#app',
data: {
num: 1,
value: '' // *
},
components: {
testInput
}
})
// 标记 //* 是重点
// 子组件中,需要 :value="value" 和 @input="$emit('input',$event.target.value)" 配合才能实现双向绑定
checkbox
// html
<div id="app">
<test-input v-model="checked"></test-input>
{{checked}}
</div>
// js
let testInput = {
// 子组件内容
name: 'testInput',
template: `
<input type="checkbox" :checked="checked" @change="$emit('change',$event.target.checked)">
`, // *
props: ['checked'], // *
model: {
prop: 'checked',
event: 'change'
}, // *
}
const app = new Vue({
el: '#app',
data: {
checked: true // *
},
components: {
testInput
}
})
// 标记 //* 是重点
// 子组件中,需要 :checked="checked" 和 @change="$emit('change',$event.target.checked)",还需要写入model