Skip to content

Instantly share code, notes, and snippets.

@ashx3s
Last active November 24, 2021 05:23
Show Gist options
  • Select an option

  • Save ashx3s/d79df284fbbb9396f9482d69107633e4 to your computer and use it in GitHub Desktop.

Select an option

Save ashx3s/d79df284fbbb9396f9482d69107633e4 to your computer and use it in GitHub Desktop.
V-model Components Example

V-Model Component Two Way Binding

This is a simple example for creating two way binding between parent and child components.

Steps to Reporduce

  1. Create a parent component with a variabe that will be used to model the component.
  2. Create a child component that features an input element
  3. add v-model to your parent component, setting it to equal the data variable
  4. Add your data binding and event handler to the input element in the child component
  5. Test by trying to render the variable used in the v-model elsewhere on the parent component

Notes

  • In the Child.vue component, you can replace the prop with value in the input element.
  • label placement
    • Inside component
      • You will need to pass the label text and name to the component from the parent
      • Benefits:
        • Uniform layout between label and component
      • Drawbacks:
        • Uniform layout between label and component (depending on your design strategy)
        • You will need to wrap the
        • Component input and label will need a wrapper, or input will need to be wrapped in label
    • Outside component
      • You will need to pass the name of the input to the component
      • Benefits:
        • Customization of how label is depicted next to the input field
        • Component input will not need a root wrapper
      • Drawbacks:
        • Must set label styles up whenever you use the component
    • An alternative to the component content wrapping would be to use a v-if/else on the template and set it to trigger one layout over the other depending on whether or not information is given for the label.
<template>
<input type="text"
v-bind:inputValue="value" v-on:input="$emit('input', $event.target.value)"
</template>
<script>
export default {
props: 'inputValue'
}
</script>
<template>
<div>
<Child v-model="message" />
<p> {{ message }} </p>
</div>
</template>
<script>
export default {
data() {
return {
message: ''
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment