Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

border style not rendering correctly when toggle style in VUE

Check this demo below:

new Vue({
	el: '#app',
  data: {
  	flag: true
  },
  computed: {
  	style() {
      let styleA  = {
          borderBottom: '1px solid red',
          borderRight: '1px solid red'
       };
       
      let styleB = {
        	border: '1px solid green',
          borderRight: '1px solid red'
      }

      return this.flag ? styleA : styleB
     
    }
  },
  methods: {
  	changeStyle() {
    	this.flag = !this.flag;
    }
  }
})
.box {
  width: 100px;
  height: 100px;
}
<html>
  <header>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
  </header>
  <body>
    <div id="app">
      <div class="box" :style="style"></div>
      <button @click="changeStyle">changeStyle</button>
    </div>
  </body>
</html>

In this demo, click changeStyle button to toggle two different styles.

Here is step:

  • First, styleA is applied with red borderBottom and red borderRight
  • Click changeStyle button, styleB is applied, green border and red borderRight are expected but only the green border is shown.

  • Click changeStyle button again, as we can see, only red borderBottom is shown, like red borderRight just disappear.

  • Click again, you will never see the red borderRight

Is something wrong with comparing virtual node and rendering in VUE?

like image 456
Clocher Zhong Avatar asked Sep 28 '18 03:09

Clocher Zhong


1 Answers

I don't really know exactly why this happens.

As you said, there's probably something wrong with the virtual DOM.

In my experience, when something is wrong with the DOM rendering in Vue, using key would solve the problem. In your case, it did. https://jsfiddle.net/jacobgoh101/Ld5e8azs/

Just add key to the div with dynamic style

<div class="box" :style="style" :key="style"></div>

key just needs to be any unique value that differentiates the 2 styles

like image 116
Jacob Goh Avatar answered Nov 14 '22 23:11

Jacob Goh