Théo Lavaux
Théo Lavaux

Reputation: 1454

Vue v-model on input as a dynamic ref

I created this <input> Vue component that handles a v-model property. Adding the two-way data binding wasn't a problem, but I now want to add the current input value to the "state" so that I can clear it by just modifying a ref.

clearValue is called as expected but updating inputValue doesn't update the UI. What should I be doing differently ?

<template>
  <div>
    <input
      :id="id"
      type="text"
      :value="inputValue"
      @input="updateValue"
    />
    <UiIcon
      type="x"
      @click.native="clearValue"
    />
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, ref } from '@nuxtjs/composition-api';
import UiIcon from '~/components/ui/UiIcon.vue';

export default defineComponent({
  name: 'UiInput',
  components: { UiIcon },
  props: {
    id: {
      type: String,
      required: true,
    },
    value: {
      type: String,
      default: undefined,
    },
  },
  setup(props, { emit }) {
    const inputValue = ref(props.value);

    const clearValue = () => {
      inputValue.value = '';
    };

    const updateValue = (event: Event) => {
      emit('input', (event.target as HTMLInputElement).value);
    };
  
    return {
      updateValue,
      clearValue,
      inputValue,
    };
  },
});

Usage example

data() {
  return { text: '' };
},
template: `
  <div>
    <UiInput :id="id" v-model="text" />
  </div>
`,

Upvotes: 1

Views: 3672

Answers (1)

iamlk
iamlk

Reputation: 74

I think you just need to emit 'input' event with empty value inside clearValue function

emit('input', '');

Upvotes: 2

Related Questions