vuejs split to string to array

Viewed 2227

I've got a string that's formatted in a textbox as comma-separated, however when I try and split it convert it to an array to loop through them I'm getting the error

Type 'string[]' is not assignable to type 'string'

My textbox (using ionic, but essentially just a textarea when rendered

<ion-textarea type="text" v-model="CSVItems" placeholder="e.g. chicken, rice, peas"></ion-textarea>

The data/methods are as follows (cut down to just necessary for the post)

 data() {
    return {
      CSVItems: "",
      myResult: "",
    };
  },
  methods: {
     addItem: function() {
      this.myResult = this.CSVItems.split(",");
  },

enter image description here

2 Answers

The error is about trying to store an array of strings to a property declared as a string. To inform tslint about the correct type, instantiate myResult as an array of strings:

data: () => ({
  CSVItems: "",
  myResult: [] as string[]
})

Additionally, you might want to also trim before assigning:

this.myResult = this.CSVItems.split(',').map(s => s.trim());

The javascript split function on a string returns an array. To turn it into a string you can use Array.join to make them a string again

Ex.


let CSVItems = "Hello,World!"

console.log(CSVItems.split(',')
// ["Hello", "World!"]


// Array.join's parameter is what to append with Ex [1,2,3].join("t") = "1t2t3"
console.log(CSVItems.split(',').join(' '))
// "Hello World!"

If you want myResult to be an array you have to set it as one


 data() {
    return {
      CSVItems: "",
      myResult: [], // Make [] not ""
    };
  },
  methods: {
     addItem: function() {
      this.myResult = this.CSVItems.split(",");
  },

Related