vue模板上的优化

用switch做感觉代码还是很多, 还有更简洁的方式吗?

<div
    class="title"
  >
    {{ orderStateValue }}
</div>


init() {
    switch (res.OrderInfo.OrderState) {
      case 'Wait':
        this.orderStateValue = '兑换成功,等待发货';
        break;
      case 'Sent':
        this.orderStateValue = '商家已发货';
        break;
      case 'Cancel':
        this.orderStateValue = '订单已取消';
        break;
      case 'Fail':
        this.orderStateValue = '订单失败';
        break;
      default:
        break;
    }
}
阅读 1.8k
3 个回答
<div class="title">
    {{ getState(state)}}
</div>
data(){
    return {
        state: 'Wait'
    }
}
methods: {
    getState(stateName){
        const states = {
            Wait: '兑换成功,等待发货',
            Sent: '商家已发货',
            Cancel: '订单已取消',
            Fail: '订单失败'
        }
        return states[stateName] || '无效状态'
    }
}

写一个 method

isShow(OrderState, state) {
 return OrderState === state
}
<div
    class="title"
    v-if="isShow(orderInfo.OrderState, 'Fail')"
  >
    订单失败
  </div>

state作key,statevalue作value,这样定义一个object对象,object中用state取值就好了

推荐问题