v-model
<input type="text" v-model="msg">
<p>{{msg}}</p>
data() {
return {
msg: 'Hello World!'
}
}
v-model实质为语法糖
语法糖:指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。通常来说使用语法糖能够增加程序的可读性,从而减少程序代码出错的机会。
v-bind:value + v-on:input实现v-model
<input type="text" :value="doMsg" @input="doMsgFun($event)"/>
<p>{{doMsg}}</p>
data() {
return {
doMsg: 'Hello World!'
}
}
methods: {
doMsgFun() {
this.doMsg = event.target.value;
}
}
或
<input type="text" :value="doMsg" @input="doMsg = $event.target.value"/>
data() {
return {
doMsg: 'Hello World!'
}
}
组件中使用时
<!-- 父组件 -->
<child @chindInput="getChildValue" :childMsg="childMsg"></child>
或
<!-- arguments是组件child里面$emit传出的值,所有的参数都会放到arguments里面,所以把获取到的auguments[0]赋值给childMsg -->
<child @chindInput="childMsg=arguments[0]" :childMsg="childMsg"></child>
data() {
return {
childMsg: 'childMsg!'
}
},
methods: {
getChildValue(value) {
this.childMsg = value;
}
}
<!-- 子组件 child.vue -->
<input type="text" @input="handleInput" :value="childMsg"/>
props: {
childMsg: String
},
methods: {
handleInput (e) {
this.$emit('chindInput', e.target.value)
}
}