vue中怎么根据传入的数据中的类型来动态设置class

我是在页面中用script标签引入的,
<!--<div class="timeBar" :class="[ {'gray-bg': data.Type==0}, {'blue-bg': data.Type==1}, {'green-bg': data.Type==2}]">-->
<div class="timeBar" :class="timeBarType(data.Type)">

在实例中用来计算属性,但是html结构上的timeBarType要求是一个对象不能是function,上面被注释掉的可以,但是我觉的太繁琐来,
computed: {

    timeBarType: function (type) {
        if(type == 0) return 'gray-bg';
        if(type == 1) return 'blue-bg';
        if(type == 2) return 'green-bg';

    }
},
阅读 13.1k
4 个回答

timeBarType写在methods中,根据传入的参数返回classname

初始化一个值
data(){
return{
type:0
}
}

返回数据时,
this.type=data.type
还是在计算属性中
computed: {

timeBarType: function () {
    if(this.type == 0) return 'gray-bg';
    if(this.type == 1) return 'blue-bg';
    if(this.type== 2) return 'green-bg';

}

},

<div class="timeBar" :class="timeBarType">

可以在请求到数据的回调中判断类型然后赋值给一个vue变量呀

可以用watch呀

<html>
    <style>
        .red {
          color: red;
        }
        .blue {
          color: blue;
        }
    </style>
    <div id="app">
        <div class="timeBar" :class="timeBarClassObj">xxx</div>
    </div>
    <script src="https://unpkg.com/vue"></script>
    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                t: 0,
                timeBarClassObj: {
                    red: true,
                    blue: false
                }
            },
            watch: {
                t(nv) {
                    this.timeBarClassObj = {
                        red: nv === 0,
                        blue: nv === 1
                    }
                }
            },
           
        })
    </script>
</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题