在 VUE 中切换样式时边框样式无法正确呈现
border style not rendering correctly when toggle style in VUE
检查下面的 demo:
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/vue@2.5.17/dist/vue.js"></script>
</header>
<body>
<div id="app">
<div class="box" :style="style"></div>
<button @click="changeStyle">changeStyle</button>
</div>
</body>
</html>
在此演示中,单击 changeStyle
按钮可切换两种不同的样式。
这是步骤:
- 首先,
styleA
应用于 red borderBottom
和 red borderRight
单击 changeStyle
按钮,应用 styleB
,预期 green border
和 red borderRight
但仅显示 green border
。
再次点击changeStyle
按钮,可以看到只显示了red borderBottom
,就像red borderRight
消失了一样。
再次点击,你将永远看不到red borderRight
在VUE
中比较虚拟节点和渲染有问题吗?
我真的不知道为什么会这样。
如您所说,虚拟 DOM 可能有问题。
根据我的经验,当 Vue 中的 DOM 渲染出现问题时,使用 key
可以解决问题。在你的情况下,确实如此。 https://jsfiddle.net/jacobgoh101/Ld5e8azs/
只需将 key
添加到具有动态样式的 div
<div class="box" :style="style" :key="style"></div>
key
只需是区分两种样式的任何唯一值
这是一个错误,但这个问题被认为是 wontfix。这是因为 border
是 shorthand 属性.
编辑:Jacob 比我快了几秒,但是,正如 gh 问题中所述,解决方法是使用 key
作为哈希来强制渲染。
替代但更丑陋的 'hack' 将区分 borderRight
样式,因此 borderRight: '1px solid red'
在 styleA
和 borderRight: '1px solid red '
中(注意空白结束)在 styleB
。
它使 vue 'think' borderRight
发生了变化,'forces' 它应用了样式(并且 'skips' 跳过了应用样式的优化步骤vue 认为已经应用)。
检查下面的 demo:
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/vue@2.5.17/dist/vue.js"></script>
</header>
<body>
<div id="app">
<div class="box" :style="style"></div>
<button @click="changeStyle">changeStyle</button>
</div>
</body>
</html>
在此演示中,单击 changeStyle
按钮可切换两种不同的样式。
这是步骤:
- 首先,
styleA
应用于red borderBottom
和red borderRight
单击
changeStyle
按钮,应用styleB
,预期green border
和red borderRight
但仅显示green border
。再次点击
changeStyle
按钮,可以看到只显示了red borderBottom
,就像red borderRight
消失了一样。再次点击,你将永远看不到
red borderRight
在VUE
中比较虚拟节点和渲染有问题吗?
我真的不知道为什么会这样。
如您所说,虚拟 DOM 可能有问题。
根据我的经验,当 Vue 中的 DOM 渲染出现问题时,使用 key
可以解决问题。在你的情况下,确实如此。 https://jsfiddle.net/jacobgoh101/Ld5e8azs/
只需将 key
添加到具有动态样式的 div
<div class="box" :style="style" :key="style"></div>
key
只需是区分两种样式的任何唯一值
这是一个错误,但这个问题被认为是 wontfix。这是因为 border
是 shorthand 属性.
编辑:Jacob 比我快了几秒,但是,正如 gh 问题中所述,解决方法是使用 key
作为哈希来强制渲染。
替代但更丑陋的 'hack' 将区分 borderRight
样式,因此 borderRight: '1px solid red'
在 styleA
和 borderRight: '1px solid red '
中(注意空白结束)在 styleB
。
它使 vue 'think' borderRight
发生了变化,'forces' 它应用了样式(并且 'skips' 跳过了应用样式的优化步骤vue 认为已经应用)。