html
<div id="app"> <input v-model="poin"> {{ poin }}</div>
js
new Vue({ el:'#app', data:{poin:'zqz' }})
Once we enter the value If something changes, the point value in data will also change.
Theoretically, an event will be triggered when the value in data changes, but we didn’t see it?
In fact, it is stated in the vue documentation:
<input v-model="something">
is the syntactic sugar below
<input v-bind:value="something" v-on:input="something = $event.target.value">
Every time we enter When the input
event is triggered, input is bound to the inline function, thus changing the value of something
.
The DOM input event is triggered synchronously when the value of the
<input>
or<textarea>
element changes. (For input elements with type = checkbox or type = radio, the input event will not fire when the user clicks the control because the value attribute does not change.) Additionally, when the content changes, it fires on the contenteditable's editor . In this case, the event target is the edit host element. If there are two or more elements with contenteditable true, the "edit host" is the nearest ancestor element whose parent is not editable. Likewise, it will also fire on the root element of the designMode editor.
For details, see: MDN input event
Accepts a value
attribute
Triggers the input
event# when there is a new value
<template> <div> <p>input的封装</p> <input type="text" ref="input" :value="value" @input="updateValue($event.target.value)" @focus="selectAll" > </div> </template> <script> export default { name: 'el-input', props: { value: { type: Number, default: 0 }, }, methods: { // 每次都会加一 updateValue (value) { this.$refs.input.value = value + 1; }, selectAll(event) { setTimeout(function () { event.target.select() }, 0) } } } </script> <style> </style>
<style> </style> <template> <!-- 在父组件中使用 --> <div> <v-el-input></v-el-input> </div> </template> <script> import vElInput from './el-input.vue' export default { name: 'tom', components: { vElInput } } </script>
input event. So we can use this feature to do something.
<template> <!-- 在父组件中使用 --> <div> <v-el-input v-model="eleValue"></v-el-input> eleValue的值:{{ this.eleValue }} </div> </template> <script> import vElInput from './el-input.vue' export default { name: 'tom', components: { vElInput }, data () { return { eleValue: 666 //设置一个默认值 } } } </script>
eleValue we expected still does not change, and the value in el-input.vue does change.
.sync in vue1, but it has been abandoned in vue2.
this.$emit('input', value*1)
...updateValue (value) { this.$refs.input.value = value + 1; // 触发组件上绑定的input事件,以实现value同步 this.$emit('input', value*1)},...
The above is the detailed content of Detailed explanation of v-model instances in components. For more information, please follow other related articles on the PHP Chinese website!