【问题标题】:Vuejs: Can't access (computed) props within computed property loopVuejs:无法在计算属性循环中访问(计算)道具
【发布时间】:2019-03-01 10:59:20
【问题描述】:

也许很明显,但我有一个 Vue 单文件组件,如下所示:

<template>
...
</template>

<script>
    export default {
        props: [ 'matches', 'results' ],

        computed: {

           formattedMatches: function () {
                let rows = [];
                this.matches.forEach(function($match, $i) {
                    rows[$i] = {
                        id: $i + 1,
                        title: $match[0] + ' ' + $match[1]
                    };
                });
                return rows;
            },

            formattedResults: function () {
                let rows = [];
                this.results.forEach(function($resultRow, $i) {
                    rows[$i] = {
                        id: $i + 1,
                        title: this.formattedMatches[$i]     
 // Error in render: "TypeError: Cannot read property 'formattedMatches' of undefined"
                    };
                });
                return rows;
            },
    ...
</script>

如果我尝试使用this.matches,也会出现错误,而不仅仅是this.formattedMatches。我想这是类和方法中变量范围的问题,但我什至不知道是否有另一种更好的方法或模式来实现相同的行为。

有什么想法吗?提前致谢。

【问题讨论】:

    标签: vue.js vuejs2 computed-properties


    【解决方案1】:

    thisforEach 的匿名函数中有不同的上下文。最简单的解决方法是使用箭头函数表示法。

    this.results.forEach(($resultRow, $i) => {
        rows[$i] = {
            id: $i + 1,
            title: this.formattedMatches[$i]
        };
    });
    

    【讨论】:

    • 感谢斯蒂芬,它也可以按预期工作。我现在已经发布了一个等效的解决方案。
    【解决方案2】:

    在 StackOverflow 上找到了基于 this other solution 的解决方案。 正如它所说,“this 在回调中指的是回调本身(或者更确切地说,正如所指出的,回调的执行上下文),而不是 Vue 实例。如果你想访问它,你要么需要将它分配给回调之外的东西”。

    所以在我的情况下......

    ...
    formattedResults: function () {
         let self = this;
         let rows = [];
         this.results.forEach(function($resultRow, $i) {
             rows[$i] = {
                  id: $i + 1,
                  title: self.formattedMatches[$i]     
             };
         });
         return rows;
    },
    ...
    

    ... 成功了。 还是谢谢!

    【讨论】:

      猜你喜欢
      • 2021-03-01
      • 2019-11-22
      • 2022-06-23
      • 2018-08-05
      • 1970-01-01
      • 2019-03-21
      • 2021-05-09
      • 2017-10-06
      • 2017-08-23
      相关资源
      最近更新 更多