2016-12-29 83 views
5

我在VueJs新手,当我想实现使用VueJs的V-绑定属性在我的Laravel项目的基本切换级功能工作。在渲染页面时,我没有获得变量className的值。请指导我在哪里做错了。下面的代码给出:Vuejs动态切换类不Laravel刀片模板

<div id="root"> 
    <button type="button" v-bind:class="{'className':isLoading}" v-on:click="toggleClass">Toggle Me</button> 
</div> 

JavaScript是:

<script> 
    var app = new Vue({ 
     el: '#root', 
     data: { 
      className:"color-red", 
      isLoading:false 
     }, 
     methods:{ 
      toggleClass(){ 
       this.isLoading=true; 
       this.className="color-blue"; 
      } 
     } 
    }) 
</script> 

风格是:

<style> 
    .color-red{ 
     background-color:red; 
    } 
    .color-blue{ 
     background-color:blue; 
    } 
</style> 

回答

0

你不能有className以及一个变量名,因为VUE预计它实际CSS类,documentation建议多一种方式,有如下类对象:

<script> 
    var app = new Vue({ 
     el: '#root', 
     data: { 
      classObj:{ "color-red" : true } , 
      isLoading:false 
     }, 
     methods:{ 
      toggleClass(){ 
       this.isLoading=true; 
       this.classObj = { "color-blue" : true}; 
      } 
     } 
    }) 
</script> 


<div id="root"> 
    <button type="button" v-bind:class="classObj" v-on:click="toggleClass">Toggle Me</button> 
</div> 
1

你正在稍微混合你的方法。主要问题在v-bind:class="{'className':isLoading}"。这个指令,你写的方式,切换一个类名"className"(字面上,而不是变量className的值),以你的元素,如果isLoadingtrue。如果它是false,它不会分配任何类。在你的代码

来看,似乎你实际上是试图取决于什么的isLoading值设置两个不同的类。最简单的方法是使用v-bind:class="isLoading ? 'color-red' : 'color-blue"。看看一个工作示例here

一个更好的解决方案,不污染与逻辑模板是该表达式移动到计算的财产,like this