代码之家  ›  专栏  ›  技术社区  ›  jabe

为什么Vue不在筛选函数中使用对此的引用来运行/更新计算属性?

  •  2
  • jabe  · 技术社区  · 8 年前

    我有一个连接到Vue计算属性的选择框。我想知道为什么我的 computed 属性尝试有效,而其他尝试无效。

    <select>
    <option v-for="option in filteredItems">{{option.description}}</option>
    </select>
    

    filteredItems 是计算属性。此代码适用于:

    vInstance = new Vue({
        ...
    
        computed: {
           filteredItems: function(){
               let someID = this.filterID;
               return this.allItems.filter(function(item){
                   return item.id === someID;
               })
           }
       }
    })
    

    此版本没有

    computed: {
        filteredItems: function(){
            return this.allItems.filter(function(item){
                return item.id === this.filterID;
            })
        }
    }
    

    除了第一个版本设置的功能外,这两个功能几乎相同 this.filterID 要在过滤器中使用的其他变量。为什么这样做有效,而另一个不行?

    1 回复  |  直到 8 年前
        1
  •  3
  •   Fatih Acet    8 年前

    这与Vue本身无关。就是这样 this 在JS中工作。在第二个代码块中, 可能会 window 因此 this.filterID 将未定义。但是在第一个代码示例中, 因此将是Vue实例 这过滤器ID 将定义。看看 this link 了解更多信息 JS中的范围。