Home  >  Q&A  >  body text

javascript - The dynamic v-bind:class that adds attributes through control in the rendering list li of vue2.0 does not take effect immediately

For example code:
The first step: Get a data object array from the server: [obj, obj, obj],
The second step: Add a browser object obj to each sub-object:

    for(let i = 0; i<array.length; i++){
        array[i].myObj = false,
    }
    添加之后的结果是每一个数组子对象obj中的属性里面就会多了一个自定义的浏览器对象属性:myObj:false

Step 3: Bind this attribute to the html structure to control the dynamic class

html:
  <ul>
      <li v-for='item in array' @click='changeBg(item)'>
          <span :class='{'change_bg':item.myObj}'>qwer</span>
      </li>
  </ul>
 js:
    methods: {
        changeBg(item){
           item.myObj = true 
        }
    }
css:
.change_bg
  background: red

The result is: the myobj attribute has been changed to true each time it is clicked, but the dynamic class will not take effect until ul is refreshed (when refreshed, the ul data will not be reacquired).

给我你的怀抱给我你的怀抱2711 days ago633

reply all(2)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-19 10:15:11

    array[i].myObj = false
    改为
    this.array.$set(i, {myObj: false})

    reply
    0
  • PHP中文网

    PHP中文网2017-05-19 10:15:11

    Correct answer upstairs. Because the attribute is added dynamically, you need to use the set method provided by vue to make the attribute an ES5 accessor attribute to track changes.

    reply
    0
  • Cancelreply