首页  >  问答  >  正文

javascript - vue 计算属性怎么传参

计算属性怎么传参?

<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 天前1672

全部回复(4)我来回复

  • phpcn_u1582

    phpcn_u15822017-07-05 10:49:14

    传不了参的,你可以写成methods

    回复
    0
  • phpcn_u1582

    phpcn_u15822017-07-05 10:49:14

    首先,计算属性里的方法是传不了参的,根据你的代码我想你想要实现的是根据type的改变去返回颜色,那么你应该明白的是计算属性返回的值只跟它里面的依赖有关,当依赖改变的时候就会触发计算属性去重新计算然后改变值,所以你应该让type变成该vm的一个数据,进而成为该计算属性的依赖。简单代码如下:

    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;
            }
        }
    }

    回复
    0
  • 大家讲道理

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

    这个需求用一个对象实例数据不就可以解决了吗?

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

    绑定 style 为 {color: colors[item.type]}

    回复
    0
  • 过去多啦不再A梦

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

    https://cn.vuejs.org/v2/guide...计算-setter

    计算属性默认只有 getter ,不过在需要时你也可以提供一个 setter :

    // ...
    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]
        }
      }
    }
    // ...

    回复
    0
  • 取消回复