javascript - How to pass parameters to vue computed properties
欧阳克
欧阳克 2017-07-05 10:47:14
0
4
1599

How to pass parameters for calculated properties?

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; } } }
欧阳克
欧阳克

温故而知新,可以为师矣。 博客:www.ouyangke.com

reply all (4)
phpcn_u1582

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

    phpcn_u1582

    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; } } }
      大家讲道理

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

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

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

        过去多啦不再A梦

        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] } } } // ...
          Latest Downloads
          More>
          Web Effects
          Website Source Code
          Website Materials
          Front End Template
          About us Disclaimer Sitemap
          php.cn:Public welfare online PHP training,Help PHP learners grow quickly!