最近项目有点忙碌,遇到好多问题都没有总结(╥﹏╥),在开发过程中,取vuex中的数组渲染完成之后,再次修改数组的值,数据更新了,但是视图并没有更新。以为是数组更新的问题,后来又以为是因为vuex导致的问题. 最后强制刷新组件解决了问题,但是还没有找到根本问题的所在

数组更新检测

  1. 在 vue 中使用数组的push()、pop()、shift()、unshift()、splice()、sort()、reverse() 、filter()、concat() 方法时,改变数组的同时可以触发视图的变化。
  2. 注意: 有两种情况 vue 无法检测到变动的数组,分别是:

(1)直接操作数组的长度;

// Vue.set
this.$set(arr, indexOfItem, newValue)
// Array.prototype.splice
this.arr.splice(indexOfItem, 1, newValue)

(2)利用索引直接设置一个项时,例如:this.arr[indexOfItem] = newValue

this.arr.splice(newLength)

demo如下:

<template>
 <div class="demo">
 <div class="list-item" v-for="item in arr[0].elements" :key="item.name">{{item.name}}</div>
 <div class="change-btn" @click="changeArr">改变列表的值</div>
 </div>
</template>

<script>
 export default {
 data() {
  return {
  index: 0,
  arr: [{
   elements: [{
   name: '0'
   }, {
   name: '1'
   }, {
   name: '2'
   }]
  }]
 
  }
 },
 methods: {
  changeArr() {
  // 可以改变数组的值
   this.arr[0].elements.push({
   name: '3'
   })
  // this.arr[0].elements[1].name = '4' 可以改变数组的值
  // this.arr[0].elements[1] = { 无法改变数组的值
  // name: '4'
  // }
  }
 }
 }
</script>

问题: 用v-for循环渲染数组数据时,数据更新了,视图却没有更新

由于 JavaScript 的限制, Vue 不能检测以下变动的数组:

\1. 当你利用索引直接设置一个项时,例如: vm.items[indexOfItem] = newValue 2. 当你修改数组的长度时,例如: vm.items.length = newLength

解决方法:

为了避免第一种情况,以下两种方式将达到像 vm.items[indexOfItem] = newValue 的效果, 同时也将触发状态更新:

// Vue.set
Vue.set(example1.items, indexOfItem, newValue) (数组, 所引, 值) 
// Array.prototype.splice`
example1.items.splice(indexOfItem, 1, newValue) (所引, 长度, 值) 

避免第二种情况,使用 splice:

example1.items.splice(newLength) 

对象更新检测

方法一:this.$set()

方法二:Object.assign()

demo.vue

<template>
 <div class="demo">
 {{object}}
 <div class="change-btn" @click="changeArr">改变列表的值</div>
 </div>
</template>

<script>
 export default {
 data() {
  return {
  index: 0,
  object: {
   name: 'haha'
  }
  }
 },
 methods: {
  changeArr() {
  // 方法一: 
   this.$set(this.object, 'age', 27)
  // 方法二:
   this.object = Object.assign({}, this.object, {
   age: 27
   })
  // 方法三: ---不可行
   this.object.age = '27'
  }
 }
 }
 </script>

补充:

this.$forceUpdate()迫使 Vue 实例重新渲染。注意它仅仅影响实例本身和插入插槽内容的子组件,而不是所有子组件。 使用 v-if 在切换时,元素及它的绑定数据和组件都会被销毁并重建

参考文献

https://cn.vuejs.org/v2/api/#vm-forceUpdate
https://cn.vuejs.org/v2/guide/list.html?#

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

©版权: https://huawenzixun.com/post/5.html

标签: 技术

你可能感兴趣

添加新评论