vue动态绑定:class,值改变,但并未动态添加类目

大概的代码,简而言之就是一个收藏按钮状态切换
image.png

<span
    class="icon-star"
    :class='{ "active" : result.isCollection==true}'
    @click="collectionHandler(result.isCollection)"
    >
</span>
collectionHandler(isCollection) {
  this.$set(this.result, 'isCollection', !isCollection)
  console.log(this.result.isCollection)
}

通过控制台可以判断当前 result.isCollection 的值是根据点击在动态变化的,但是:class绑定的类并没有动态添加,想问是什么原因?

阅读 4.3k
3 个回答
:class='{ "active" : result.isCollection}'
<template>
  <div id="app">
    <span
      class="icon-star"
      :class="{ active: result.isCollection == true }"
      @click="collectionHandler(result.isCollection)"
    >
    </span>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      result: {
        isCollection: false,
      },
    };
  },
  methods: {
    collectionHandler(isCollection) {
      console.log(isCollection)
      this.$set(this.result, "isCollection", !isCollection);
      console.log(this.result.isCollection);
    },
  },
};
</script>

<style>
.icon-star {
  display: block;
  width: 100px;
  height: 100px;
  background: lightblue;
}
.active {
  background: red;
}
</style>

按你这个试下是可以的

用一个计算属性返回
result.isCollection
然后
:class="{ active : 你的计算属性}"
试试

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题