Home > front end >  Vue how to split string by comma and save as array
Vue how to split string by comma and save as array

Time:05-28

I'm a Ruby guy who is trying to get some Vue knowladge. In my projecy user can provide multiple styleCodes via input field - each of the styleCode is separated by a comma. I want to store this styleCodes in array to calculate its length freely. I've below:

<template>
  <form>
    <input type="text" v-model="tempStyleCodes">
  </form>
  <button
    type="button"
    @click="syncProducts"
  >
    Sync
  </button>
</template>

<script>

export default {
  name: 'SyncProducts',
  data() {
    return {
      styleCodes: [],
      tempStyleCodes: '',
    }
  },
  computed: {
    productsToSyncAmount () {
      this.tempStyleCodes.split(',')
      this.styleCodes.push(this.tempStyleCodes)
      return this.styleCodes.length
    }
  },
  methods: {
    async syncProducts() {
      let confirmationText = `Do you want to ${this.productsToSyncAmount} sync products?`
      this.loadId = null

      if (this.productsToSyncAmount === 0) {
        ModalController.showToast('', 'Type product codes for sync first, please!', 'warning')
      }
      // (...) some ohter irrelevant code
    },
  }
}

I think I'll need something similar to Ruby method .split(',') because my code for sample input of 4321test, test, 908test produces:

styleCodes: [ "4321test, test, 908test" ]

Where length will give me 1 element instead of 3.

So desired result should be:

styleCodes: [ "4321test", "test", "908test" ]

How to split these values?

CodePudding user response:

You can use split function:

const styleCodes = [ "4321test, test, 908test" ]
console.log(styleCodes[0].split(','))

CodePudding user response:

You can use String's split() method, which can take either a string or a regular expression as the separator.

const codes = this.tempStyleCodes.split(/\s*,\s*/);

Now that you have an array of codes, you can push all of them in styleCodes by using the spread syntax (see browser compatibility) which is accepted by Array's push() method:

this.styleCodes.push(...codes);

Example:

const styleCodes = [];
const tempStyleCodes = "4321test, test, 908test";

const codes = tempStyleCodes.split(/\s*,\s*/);
styleCodes.push(...codes);

console.log(styleCodes);

CodePudding user response:

as you are using the split function to check the length of the string i assume your issue isn't how to split the value but how to bind to it

in which case i suggest use a writable computed value

computed: {
  formattedStyleCodes {
    get(){
      return this.tempStyleCodes.join(",")
    }
    set(value){
      this.tempStyleCodes = value.split(',')
    }
  }
},

you can then bind to it as

<input type="text" v-model="formattedStyleCodes ">
  • Related