[Vuejs]-Vue: How do you bind a value to an input through a wrapper component?

1πŸ‘

βœ…

The best way is use v-model for wrapper and on/emit for input

<div id="Login">
    <Input v-model="email"/>    
    <Input v-model="password"/>    
</div>

…

<div class="input>       
   <input        
     v-bind:value="value"
     v-on:input="$emit('input', $event.target.value)"
   >
</div>

2πŸ‘

If I got it correctly, you can try to create transparent wrapper (in my case AppInput)

SomeParent.vue

<div>
  <AppInput v-model="parentModel" />
</div>

AppInput.vue

<template>
  <input
    class="app-input"
    v-bind="$attrs"
    :value="value"
    v-on="{
      ...$listeners,
      input: event => $emit('input', event.target.value)
    }">
</template>
<script>
export default {
  name: "AppInput",
  inheritAttrs: false,
  props: ["value"]
};
</script>

one of articles

1πŸ‘

You can implement v-model directly in the input component by doing so.

<template>
  <div class="input>
   <input :value="value" @input="$emit('input', $event.target.value)"/>
  </div>
</template>
<script>
  export default {
    name: 'Input',
    props: ["value"]
  }
</script>

And then use it in your parent component like this:

<template>
  <div id="Login">
    <Input v-model="email"/>    
    <Input v-model="password"/>
  </div>
</template>
<script>
  import Input from './Input.vue'
  import Button from './Button'

  export default {
    name: 'Login',
    components: {
        Input,
        Button,
    },
    data: () => ({
        email:'test',
        password:'test',
    }),
    methods: {
        login: () => { debugger; }, //this.email and this.password are still set to test
    }
  }
</script>

See here

πŸ‘€Pierre Said

Leave a comment