简体   繁体   English

vuejs 拆分为字符串到数组

[英]vuejs split to string to array

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(",");
  },

在此处输入图像描述

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:要告知 tslint 正确的类型, myResult实例化为字符串数组:

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. javascript 在字符串上拆分 function返回一个数组。 To turn it into a string you can use Array.join to make them a string again要将其转换为字符串,您可以使用Array.join再次使它们成为字符串

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如果您希望 myResult 成为一个数组,则必须将其设置为一个


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM