编程语言
首页 > 编程语言> > Javascript-为什么v-show和v-if立即响应对象中的布尔更改,而不响应数组中的布尔更改?

Javascript-为什么v-show和v-if立即响应对象中的布尔更改,而不响应数组中的布尔更改?

作者:互联网

在开发动态的FAQ页面时会遇到这种奇怪的行为,在该页面上单击问题后将显示答案.

当控制答案的打开/关闭的布尔值存储在对象中时,视图将立即更新,并且答案会立即显示或隐藏.但是,当将其存储在列表中时,除非以其他方式更新视图,否则答案不会显示或隐藏.

这是显示问题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://vuejs.org/v2/guide/list.html#Array-Change-Detection

如上面的链接所述,您必须改为使用splice():

questionarray.splice(2, 1, !questionarray[2])

标签:vue-js,frontend,vuejs2,javascript
来源: https://codeday.me/bug/20191111/2018682.html