【问题标题】:Vue doesn't rerender binded class when data changes数据更改时,Vue 不会重新渲染绑定的类
【发布时间】:2019-06-27 06:21:28
【问题描述】:

当数据改变时,Vue 不会重新渲染绑定的类

我用默认值声明数据'isLoading'并绑定在html标签中,还声明了更改数据的方法。

请看下面的代码!

风格

  .is-red{
    background: red;
  }
  .is-blue{
    background: blue;
  }

脚本

export default {
    created() {
      this.isLoading = true;
    },
    mounted() {

    },
    data() {
      return {
        isloading: true
      };
    },
    methods: {
      changeColor() {
        this.isLoading = !this.isLoading;
        console.log(this.isLoading);
      }
    }
  }

html

<h1 v-bind:class="{'is-blue': isLoading, 'is-red': !isLoading }">hello</h1>
<button @click="changeColor">toggle</button>

我可以在控制台日志中看到“真”和“假”之间的数据切换。但是 DOM 没有任何变化。

有什么问题?

【问题讨论】:

  • 所以你的背景总是蓝色的?您可以尝试不使用单引号吗:&lt;h1 v-bind:class="{is-blue: isLoading, is-red: !isLoading }"&gt;hello&lt;/h1&gt;
  • @SimonThiel 是的,即使值发生变化,它也总是蓝色的。而且没有引号也不能工作:'(

标签: vue.js dynamic data-binding


【解决方案1】:

您使用名称isloading 声明了您的变量。 而你在 created.Vue 中声明 isLoading 不会观察动态变量的变化。

要更新组件内的动态变量,请使用Vue.set()this.$set()

你的脚本:

export default {
    mounted() {

    },
    data() {
      return {
        isLoading: true
      };
    },
    methods: {
      changeColor() {
          this.isLoading = !this.isLoading;
      }
   }
}

【讨论】:

    【解决方案2】:

    尝试使用computed,如下所示

    脚本

    export default {
        data() {
            return {
                isloading: true
            };
        },
        computed:{
            classes(){
                return this.isloading ? 'is-blue' : 'is-red';
            }
        },
        methods: {
            changeColor() {
                this.isLoading = !this.isLoading;
                console.log(this.isLoading);
            }
        }
    }
    

    html

    <h1 :class="classes">hello</h1>
    <button @click="changeColor">toggle</button>
    

    【讨论】:

      猜你喜欢
      • 2023-01-10
      • 2021-07-29
      • 2019-09-22
      • 2020-09-18
      • 2023-04-09
      • 2018-10-14
      • 2020-07-09
      • 2019-07-30
      • 2020-12-25
      相关资源
      最近更新 更多