Skip to content

Instantly share code, notes, and snippets.

@tinyfly
Created February 14, 2020 00:59
Show Gist options
  • Save tinyfly/3a74281b210dc56cfa962e1660f48f91 to your computer and use it in GitHub Desktop.
Save tinyfly/3a74281b210dc56cfa962e1660f48f91 to your computer and use it in GitHub Desktop.
In VueJS, use a computed property setter as an easy way to pass down v-model within your component without using watchers.
<template>
<div class="form-group">
<label :for="uid"><slot></slot></label>
<input :id="uid" type="text" v-model="innerValue">
</div>
</template>
<script>
/**
* Custom text input component
* @example
* <TextInput v-model="fields.name">First Name</TextInput>
*/
export default {
props: {
// passed in with v-model
value: {
type: String,
default: ''
}
},
computed: {
// allows us to use v-model within this component
innerValue: {
get () {
return this.value;
},
set (newVal) {
this.$emit('input', newVal);
}
}
},
beforeCreate () {
// create a unique ID to tie labels and inputs together without
// having to manually set the id through a prop
this.uid = `TextInput-${Math.random().toString(36).slice(2, 12)}`;
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment