简体   繁体   English

为什么 v-bind:class 不起作用?

[英]Why v-bind:class not working?

I'm learning v-bind:class in VueJS but I've encountered some problems with it.我正在学习 v-bind:class 在 VueJS 中,但我遇到了一些问题。 Here are my code这是我的代码

 var myApp = new Vue({ el: "#result", data: { isActive: true } });
 .red { color: red }
 <script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script> <div id="result"> <p v-bind:class="{red: isActive}">Hello</p> </div>

Was there any problems with my code above?我上面的代码有什么问题吗? As I want the result to be因为我希望结果是

<div class="red"></div>

Thanks in advance!提前致谢!

It works perfectly, see the codepen example:它完美运行,请参阅 codepen 示例:

https://codepen.io/martiensk/pen/boBPKQ https://codepen.io/martiensk/pen/boBPKQ

The generated code is:生成的代码是:

<div id="result">
    <p class="red">Hello</p>
</div>

The problem is not with your Vue code, but elsewhere.问题不在于您的 Vue 代码,而在于其他地方。

 var myApp = new Vue({ el: "#result", data: function(){ return { isActive: true } } });
 .red { color: red }
 <script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script> <div id="result"> <div v-bind:class="{red: isActive}">Hello</div> </div>


Data only accepts Function when used in a component definition.当在组件定义中使用时,数据只接受函数。

data: function(){
    return {
        isActive: true
    }
}

https://v2.vuejs.org/v2/api/#Options-Data https://v2.vuejs.org/v2/api/#Options-Data

Please Run this code on JsFiddle Online Editor.请在 JsFiddle 在线编辑器上运行此代码。 Link关联

<div id="app">
   <div class="box" :class="{bgColor: attache}" @click="attache = !attache">
     <p class="text" :class="{'txt-color': attache}">
       3
     </p>
   </div>
</div>

CSS Code CSS 代码

.box {
  height: 70px;
  width: 70px;
  background-color: green;
  display:flex;
  flex-direction: row;
  justify-content: center;
  align-items:center;
  cursor: pointer;
}

.text {
  font-size:18px;
  color: white;
}

.bgColor {
  background-color: #e8eaed;
}

.txt-color {
  color: #000;
}

JavaScript JavaScript

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    attache: false
  }
})

Clear you cache it will work perfectly.清除您的cache ,它将完美运行。

Check it in Browser Incognito Mode.在浏览器隐身模式下检查它。

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

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