【问题标题】:Vuejs dynamically toggle class is not working in Laravel Blade TemplateVuejs 动态切换类在 Laravel Blade 模板中不起作用
【发布时间】:2017-05-13 12:13:21
【问题描述】:

我是 VueJs 的新手,因为我试图在我的 Laravel 项目中使用 VueJs 的 v-bind 属性来实现基本的切换类功能。在呈现页面时,我没有得到变量 className 的值。请指导我哪里做错了。代码如下:

<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>

【问题讨论】:

    标签: javascript php laravel vue.js


    【解决方案1】:

    您正在稍微混合您的方法。主要问题在v-bind:class="{'className':isLoading}"。如果isLoadingtrue,则该指令(按照您编写它的方式)将名称为"className"(字面意思是,不是变量className 的值)的类切换到您的元素。如果是false,则不分配任何类。

    查看您的代码,您似乎实际上是在尝试根据isLoading 的值设置两个不同的类。最简单的方法是使用v-bind:class="isLoading ? 'color-red' : 'color-blue"。看看一个工作示例here

    不污染您的模板的更好的解决方案是将该表达式移至计算属性like this

    【讨论】:

      【解决方案2】:

      你不能有 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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-21
        • 2019-06-26
        • 1970-01-01
        • 1970-01-01
        • 2017-07-31
        • 2020-05-26
        • 1970-01-01
        相关资源
        最近更新 更多