【问题标题】:Conditional filterBy for v-for loop using Child elements data使用子元素数据的 v-for 循环的条件 filterBy
【发布时间】:2016-04-04 15:35:39
【问题描述】:

我有一组从 api 获取的项目。下面是我从服务器接收到的数据示例。

{
    {"name": "example1", "price": 11, "vendor": "vendor_name1" },
    {"name": "example2", "price": 12, "vendor": "vendor_name2" },
    {"name": "example3", "price": 13, "vendor": "vendor_name3" },
}

每个循环项都分配有数据属性edit: false,根据偏好从假切换到真。有没有办法设置选择性的“filterBy”,它可以只过滤带有edit:false的项目并跳过过滤edit:true?

请看示例:

Code Pen

谢谢。

【问题讨论】:

  • 您可以使用 edit:false 和 var noEdit = obj.filter(function(x) { return !x.edit }) 获取所有对象,然后对该结果执行您需要的任何计算。
  • 问题是对象被传递给子组件。并且 edit:false 是从内部分配的。并且 vue.js 没有从父范围中看到该属性。它只看到从服务器获取的属性。

标签: javascript vue.js


【解决方案1】:

我通过克隆我编辑的项目来实现它。通过添加 $removeBy 方法和 $clone

Vue.prototype.$removeBy = ( arr, key, val ) => {
    let index = arr.findIndex( ( e ) => e[ key ] === val );
    if ( index > -1 ) {
        arr.splice( index, 1 );
    }
};

Vue.prototype.$clone = ( obj ) => {
    var target = {};
    for ( var i in obj ) {
        if ( obj.hasOwnProperty( i ) ) {
            target[ i ] = obj[ i ];
        }
    }
    return target;
};

工作示例在这里。

CodePen

【讨论】:

    【解决方案2】:

    您可以设置自定义过滤器:http://vuejs.org/guide/custom-filter.html

    Vue.filter('editing',function(obj){
      return !obj.edit;
    });
    

    那么在你看来,它会是这样的:

    <div v-for="product in products | editing"></div>
    

    【讨论】:

    • 它不起作用,因为从子元素中分配的“编辑”属性和父元素不知道它。您的过滤器将不会返回任何内容,因为 products 数组中没有编辑这样的属性。请参阅CodePen 示例。
    • 您需要将更改同步回父级。而不是分配像:products="products" 这样的道具做:products.sync="products"(或您在子组件上为您的属性设置的任何名称)
    • 如果要在数组上使用filterBy,则需要将edit 设为产品对象的属性。如果需要,您可以在 Product 组件上的 ready() 函数中执行此操作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 2019-06-02
    • 2021-12-30
    • 2020-08-13
    • 2019-05-09
    • 2021-01-06
    • 2021-06-03
    相关资源
    最近更新 更多