代码之家  ›  专栏  ›  技术社区  ›  Andrew Li

Vue V-Bind:更改绑定对象的值时类不立即工作

  •  1
  • Andrew Li  · 技术社区  · 7 年前

    在Vue中,为了向元素添加动态类,我认为开发人员使用 v-bind:class .
    但在下面的示例中, V型绑定:类 工作不正常。

    //Html
    <div id="mainapp">
      <span class="star" v-bind:class="{gold:obj.selected}" v-on:click="clickStar()">star</span>
    </div>
    
    //Script
    var app = new Vue({
      el:"#mainapp",
      data:{
        obj:{}  
      },
      methods:{
        clickStar:function(){
          if(this.obj.selected == undefined) this.obj.selected =false;
          //this.obj.selected=!this.obj.selected;
          this.$set(this.obj, 'selected', !this.obj.selected);
          console.log(this.obj);
        }
      }
    })
    

    JsFiddle Example

    单击元素时, span 标签 obj.selected 值被更改 clickStar 功能。
    但是v-bind:但是类不起作用 $set 用于更改 obj .
    Reason that Dom is not updated
    我怎么了? 我如何解决这个问题?

    2 回复  |  直到 7 年前
        1
  •  0
  •   Brian Lee    7 年前

    组合类属性:

    :class="`star ${obj.selected ? 'gold' : ''}`"
    
    methods:{
      clickStar () {
        if (this.obj.hasOwnProperty('selected') {
          this.obj.selected = !this.obj.selected
        } else {
          this.$set(this.obj, 'selected', true);
        }
      }
    }
    

    Adding reactive properties

    另一种方法是使用 ref :

    <span ref="star" class="star" @click="clickStar">star</span>
    
    methods:{
      clickStar () {
        if (this.obj.hasOwnProperty('selected') {
          this.obj.selected = !this.obj.selected
        } else {
          this.$set(this.obj, 'selected', true);
        }
    
        if (this.obj.selected) {
          this.$refs.star.$el.classList.add('gold')
        } else {
          this.$refs.star.$el.classList.remove('gold')
        }
      }
    }
    
        2
  •  0
  •   hema sundar Ginni    7 年前

    您应该在数据属性的首字母签名时定义它。

    将数据对象更改为。

    data : { object: { selected:false
    } }

    小提琴更新 js fiddle