在开发动态 FAQ 页面时遇到了这种奇怪的行为,该页面在单击问题后显示答案。
当控制答案打开/关闭的 bool 值存储在对象中时, View 会立即更新,答案会立即显示或隐藏。但是,当它存储在列表中时,直到以其他方式更新 View 时,才会显示或隐藏答案。
这是一个显示问题的 fiddle https://jsfiddle.net/masterofginseng/ffqt9n4y/6/
HTML
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<div id="faq">
<div>This responds immediately</div>
<hr>
<div v-for="questionObj in questions1">
<div style="cursor: pointer;" @click="questionObj.open = !questionObj.open">
{{ questionObj.question }}
</div>
<div style="color: blue;" v-show="questionObj.open">{{ questionObj.answer }}</div>
</div>
<br>
<br>
<div>This doesn't respond until the view is updated in some other way (ex. by clicking on one of the questions above)</div>
<hr>
<div v-for="questionarray in questions2">
<div style="cursor: pointer;" @click="questionarray[2] = !questionarray[2]">
{{ questionarray[0] }}
</div>
<div style="color: blue;" v-show="questionarray[2]">{{ questionarray[1] }}</div>
</div>
</div>
和 javascript:
new Vue({
el: "#faq",
data: {
questions1: [{
question: "How big is it?",
answer: "very big",
open: false
}, {
question: "How small is it?",
answer: "very small",
open: false
}],
questions2: [
["How big is it?", "very big", false],
["How small is it?", "very small", false]
]
}
});
最佳答案
由于 Javascript 的限制,Vue 无法使用以下语法检测项目中值的变化:
questionarray[2] = !questionarray[2]
参见此处:https://v2.vuejs.org/v2/guide/list.html#Array-Change-Detection
如上面链接中所述,您必须改用 splice()
:
questionarray.splice(2, 1, !questionarray[2])
关于javascript - 为什么 v-show 和 v-if 会立即响应对象中的 bool 值变化,而不是数组中的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44544061/