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; } } }
If the parameters cannot be passed, you can write them as methods
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:
Can’t this requirement be solved with an object instance data?
Bind style to
{color: colors[item.type]}
https://cn.vuejs.org/v2/guide... calculation-setter