简体   繁体   English

如何在vue.js 2上添加类?

[英]How to add class on vue.js 2?

My component is like this : 我的组件是这样的:

<template>
    <span class="rating">
        ...
    </span>
</template>
<script>
    export default{
        props: {
            'star': null
        }, 
        created: function() {
            if(this.star != null)
                $(".rating").addClass('test');
        }
    }
</script>

When the page reload first, I want to check prop star. 当页面第一次重新加载时,我要检查道具星。 If the prop star not equal to null, then add class test 如果道具星不等于null,则添加类别测试

I try like my code above, but it does not work 我尝试使用上面的代码,但无法正常工作

Is there anyone who can help me? 有谁可以帮助我吗?

You don't need to use jQuery for that. 您不需要为此使用jQuery。

<template>
    <span :class='{"rating": star !== null}'>
        ...
    </span>
</template>
<script>
    export default{
        props: {
            'star': null
        }
    }
</script>

:class is property binding syntax, you can say that it is now able to access the variables in your vue-component . :class是属性绑定语法,可以说它现在可以访问vue-component的变量。

{'rating': star !== null} this simple boolean expression will ensure if .rating has to be added or not. {'rating': star !== null}这个简单的布尔表达式将确保是否必须添加.rating

You can also do something like: 您还可以执行以下操作:

:class='{"rating": !!star}'

If the expression evaluates to a truthy, you will get the class applied. 如果表达式的计算结果为真,则将应用该类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM