【问题标题】:How to create array of strings in VueJS?如何在 VueJS 中创建字符串数组?
【发布时间】:2020-07-27 16:15:59
【问题描述】:

我正在使用 VueJS 和 Vuetify 创建一个可以在文本字段中接受一些字符串的模式。现在我想做的是将输入字符串推入数组on click。因此,假设我输入一些内容并单击创建结果数组是['inputValue1'],但如果我通过用逗号分隔添加另一个值,结果数组应该是['inputValue1', 'inputValue2'],而不是我得到它作为['inputValue1', 'inputValue1' 'inputValue2']。所以应该将新值推送到新索引,而不是与最后一个值相加。

这是demo

new Vue({
  el: "#app",
  data() {
    return {
      dialog: false,
      inputValue: "",
      stringArray: []
    };
  },
  methods: {
    createArray() {
      if (this.inputValue !== "") {
        this.stringArray.push(this.inputValue);
        console.log(this.stringArray);
      }
    },
    closeDialog() {
      this.dialog = false;
      this.inputValue = "";
      this.stringArray = [];
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.js"></script>

<div id="app">
  <v-app id="inspire">
    <v-layout justify-center>
      <v-flex>
        <v-btn color="primary" @click="dialog=!dialog"> Click Me </v-btn>
      </v-flex>
    </v-layout>
    <v-dialog v-model="dialog" width=350>
      <v-card>
        <v-card-title primary-title>
          Create Array
        </v-card-title>
        <v-card-text>
          <span class="title">How to create Array of Strings </span>
          <v-layout justify-center>
            <v-flex xs11>
              <v-text-field v-model="inputValue"></v-text-field>
            </v-flex>
          </v-layout>
        </v-card-text>
        <v-card-actions class="mt-5">
          <v-spacer></v-spacer>
          <v-btn @click="closeDialog">CLOSE</v-btn>
          <v-btn @click="createArray" :disabled="this.inputValue === ''" color="primary">CREATE</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-app>
</div>

还有on Cancel 如何将输入值和数组分别设置为空字符串和空数组。谢谢。我昨天问过,但由于我无法弄清楚确切的问题,所以不得不删除。

【问题讨论】:

  • 不确定您的问题是什么,createArray 方法将字符串正确添加到数组中。您没有将它附加到任何点击事件
  • 哎呀,很好。修复。大声笑,解决了这个问题。
  • @Eggon 非常感谢!!有时我想这就是你所需要的。
  • 如果您将其添加为答案,我很乐意接受。
  • 不客气 :)

标签: javascript arrays vue.js


【解决方案1】:

您的“createArray”方法未附加到任何点击事件。除此之外,代码是正确的。 :)

【讨论】:

    【解决方案2】:

    你应该在将值推送到数组后清除 inputValue,如下所示:

    methods: {
    createArray() {
      if (this.inputValue !== "") {
        this.stringArray.push(this.inputValue);
        this.inputValue = '';
        console.log(this.stringArray);
      } else {
      console.log('The inputValue is empty')
     }
    },
    closeDialog() {
      this.dialog = false;
      this.inputValue = "";
      this.stringArray = []
    }
    }
     });
    

    【讨论】:

    • yup 也应用了这个。谢谢!!
    猜你喜欢
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    相关资源
    最近更新 更多