Search code examples
vue.jstextareabootstrap-vue

Vue Bootstrap Array of strings comma seperated from text area?


I need to extract strings from a text area in vue bootstrap and save them into an array. These are number and alpha strings, and when someone puts a coma they separate. Bonus if we could do it so they appear are 'pills' or tags in a tag add input field. Read the documentation could not find anything specifically for this, thanks so much for any help.


Solution

  • The splitting shouldn't be too difficult, just manually bind the input and parse the output from the textarea, converting to and from the data array appropriately for each.

    For the textarea's input value:

    • Concat the array elements together, with , separating each element
    • We can use list.join(', ') to accomplish this

    For the textarea's output value:

    • We can bind a handler to one of the events that Bootstrap-Vue's textarea emits, in this case I used update since that's what BV uses for v-model
    • That handler will translate the text into our array:
      • Split the sting into an array on commas: value.split(",")
      • Trim each element to remove preceding/ trailing whitespace: .map(item => item.trim())
      • Then filter out any empty elements: .filter(item => item.length > 0)

    This input/ output logic will appropriately translate the textarea's contents into an array and vice-versa.

    As for the pills, I'm not sure if what I've done below is exactly what you're looking for, but I thought I'd give it a shot.


    Functioning Example

    new Vue({
      el: '#app',
      data() {
        return {
          listArr: ["test", "1", "2"],
        }
      },
      computed: {
        arrToText() {
          return this.listArr.join(', ');
        },
      },
      methods: {
        textToArr(value) {
          this.listArr = value.split(",")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        },
      },
    });
    <!-- Set up Vue and Bootstrap-Vue for snippet -->
    <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap@4/dist/css/bootstrap.min.css" /><link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" /><script src="//unpkg.com/vue@2/dist/vue.min.js"></script><script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
    
    <div id="app">
      <b-form-textarea :value="arrToText" class="mb-2" @update="textToArr"></b-form-textarea>
      <h3>
        <b-badge v-for="(item, index) in listArr" :key="index" pill variant="primary" class="mr-2">{{ item }}</b-badge>
      </h3>
    </div>