How databind a textarea component text value and update it?

Viewed 7619

I've been working on VueJS just 1 weeks ago for a project.

I've created two components: * Account.vue (Parent)

<!--It's just a little part of the code-->
 <e-textarea
    title="Informations complémentaires"
    @input="otherInformation" <!--otherInformation is a string variable which contains the text value-->
    :value="otherInformation"></e-textarea>

  • TextArea.vue (Children Component)
<template>
  <div class="form-group">
    <label for="e-textarea">{{ title }}</label>
    <textarea
      id="e-textarea"
      class="form-control"
      row="3"
      :value="value"
      v-on="listeners"
    >
    </textarea>
  </div>
</template>
<script>
import { FormGroupInput } from "@/components/NowUiKit";

export default {
  name: "e-textarea",
  components: {
    [FormGroupInput.name]: FormGroupInput
  },
  props: {
    title: String,
    value: String
  },
  computed: {
    listeners() {
      return {
        ...this.$listeners,
        input: this.updateValue
      };
    }
  },
  methods: {
    updateValue(value) {
      this.$emit("input", value);
    }
  },
  mounted() {
    console.log(this.components);
  }
};
</script>

<style src="@/assets/styles/css/input.css" />

When I write something in my TextArea Custom component from my Account.vue, my text value does not update and my listener function is not passed. Does I need to have something else?

2 Answers

You can easily do this by v-model:

<textarea
  id="e-textarea"
  class="form-control"
  row="3"
 v-model="value"
>
</textarea>

it's equals to:

<textarea
  id="e-textarea"
  class="form-control"
  :value="value"
  @input="value = $event.target.value"> </textarea>

Bind the value in your custom textarea and the input event:

CustomTextarea.vue

<template>
  <div class="form-group">
    <label for="e-textarea">{{ title }}</label>
    <textarea
      id="e-textarea"
      class="form-control"
      row="3"
      v-bind:value="value"
      v-on:input="$emit('input', $event.target.value)"
    >
    </textarea>
  </div>
</template>
<script>
import { FormGroupInput } from "@/components/NowUiKit";

export default {
  name: "e-textarea",
  components: {
    [FormGroupInput.name]: FormGroupInput
  },
  model: {
    prop: "textAreaVue"
  },
  props: {
    title: String,
    value: String
  },
  computed: {
    listenerFunction() {
      return {
        ...this.$listener,
        input: this.updateValue
      };
    }
  },
  methods: {
    updateValue(value) {
      console.log("function has been passed");
      this.$emit("input", value);
    }
  },
  mounted() {
    console.log(this.components);
  }
};
</script>

<style src="@/assets/styles/css/input.css" />

And use it with v-model :

<custom-textarea
    title="Informations complémentaires"
    v-model="otherInformation"></custom-textarea>

More explanation here

Related