Home  >  Q&A  >  body text

javascript - How to pass parameters to vue computed properties

How to pass parameters for calculated properties?

<ul>
    <li v-for="item in goods" :style="goodsType" v-text="item.name"></li>
</ul>

data: {
    goods: [{
        id: 2,
        type: 3,
        name: '薯片'
      },{
        id: 3,
        type: 5,
        name: '冰红茶'    
    }]
},
computed: {
    goodsType: function(type){
        switch (type) {
            case 3:
                return "color: #ff9900"
                break;
            case 5:
                return "color: #00BC0C"
                break;
        }
    }
}
欧阳克欧阳克2662 days ago1673

reply all(4)I'll reply

  • phpcn_u1582

    phpcn_u15822017-07-05 10:49:14

    If the parameters cannot be passed, you can write them as methods

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-07-05 10:49:14

    First of all, the method in the calculated attribute cannot pass parameters. According to your code, I think what you want to achieve is to return the color according to the change of type. Then you should understand that the value returned by the calculated attribute is only related to the value in it. Dependencies are related. When dependencies change, the calculated property will be triggered to recalculate and then change the value, so you should make type a data of the vm, and then become a dependency of the calculated property. The simple code is as follows:

    data: {
        goods: [],
        type: 0  //这个type作为你后面计算属性的依赖项,通过其他方法改变它的值即可。
    },
    computed: {
        goodsType: function(){
            //这里将会依赖于此vm的type值,当type值改变,就会重新计算
            switch (this.type) {
                case 3:
                    return "color: #ff9900"
                    break;
                case 5:
                    return "color: #00BC0C"
                    break;
            }
        }
    }

    reply
    0
  • 大家讲道理

    大家讲道理2017-07-05 10:49:14

    Can’t this requirement be solved with an object instance data?

    colors: {
      3: '#ff9900',
      5: '#00BC0C'
    }

    Bind style to {color: colors[item.type]}

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-07-05 10:49:14

    https://cn.vuejs.org/v2/guide... calculation-setter

    Computed properties only have getters by default, but you can also provide a setter when needed:

    // ...
    computed: {
      fullName: {
        // getter
        get: function () {
          return this.firstName + ' ' + this.lastName
        },
        // setter
        set: function (newValue) {
          var names = newValue.split(' ')
          this.firstName = names[0]
          this.lastName = names[names.length - 1]
        }
      }
    }
    // ...

    reply
    0
  • Cancelreply