【问题标题】:Access returned computed array within method and manipulate在方法中访问返回的计算数组并​​进行操作
【发布时间】:2018-03-04 18:37:08
【问题描述】:

我有一个计算数组,其中充满了标签和更新,具体取决于我在选择框中所做的选择。我想获取这个数组并将其传递给一个方法,然后运行一个方法来更新具有活动类的“结果”。虽然我得到一个数组说我不能在这个元素上运行 forEach。

通过一些主题并了解计算属性不是这样工作的,但肯定有办法解决这个问题。

https://jsfiddle.net/39jb3fzw/6/

短片

methods: {
        updateOutput() {
          var tags = this.tagArray;
          tags.forEach(function(tag) {
            console.log(tag);
          })
        }
    },
    computed: {
        concatenated: function () {
            var ret = this.selected.concat(this.selected2, this.selected3);
            this.tagArray = ret;
            //this.updateOutput();
            return ret;
        }
    }

完整输出

https://jsfiddle.net/39jb3fzw/6/

再次感谢 :slight_smile:

【问题讨论】:

    标签: arrays methods foreach vue.js computed-properties


    【解决方案1】:

    看起来问题出在这条线上:

    var ret = this.selected.concat(this.selected2, this.selected3);

    那行代码返回的是一个空字符串而不是一个数组。这是因为this.selectedX 是一个字符串而不是一个数组。这解释了为什么 tag.forEach 未定义。 forEach 不存在于 String 原型中。

    你可以创建一个数组来代替

    var ret = [ this.selected, this.selected2, this.selected3 ]

    从那里您可以将this.tagArray 设置为ret

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2013-08-28
      • 2013-09-09
      • 1970-01-01
      • 2023-01-30
      • 2019-12-27
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 2021-09-09
      相关资源
      最近更新 更多