Created
July 24, 2017 06:41
-
-
Save Jokcy/0789228b25d73f6a017b0b04e01ae34a to your computer and use it in GitHub Desktop.
vue controlled input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default { | |
props: { | |
value: { | |
type: [String, Number], | |
default: '', | |
}, | |
}, | |
data() { | |
return { | |
currentValue: `${this.value}` | |
} | |
}, | |
watch: { | |
value(val, oldVal) { | |
if (val !== oldVal) { | |
this.$refs.input.value = val | |
} | |
}, | |
}, | |
methods: { | |
handleChange(e) { | |
this.$emit('change', e.target.value) | |
}, | |
handleInput(e) { | |
e.preventDefault() | |
let value = this.currentValue = e.target.value | |
this.$refs.input.value = this.value | |
this.$emit('input', value) | |
}, | |
}, | |
render(h) { | |
const on = { | |
change: this.handleChange, | |
input: this.handleInput, | |
} | |
const attrs = { | |
on, | |
} | |
return ( | |
<input type="text" {...attrs} value={this.currentValue} ref="input"/> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment