美文网首页
Vue数组变化视图不刷新 方案汇总

Vue数组变化视图不刷新 方案汇总

作者: 风凌摆渡人 | 来源:发表于2019-10-30 11:31 被阅读0次

背景

简单做个冒泡排序的效果,vue数据交换过后视图不刷新


demo效果

解决方案总结

序号 方法 备注
1 对数据进行拆装箱 相当于直接更新数据
2 Vue.set(target, key, value) vue提供的方法简洁明了
3 对item进行组件封装使用watch监听 针对于内容复杂的个人推荐

栗子🌰

<template>
  <div class="bubbling">
    <div class="report">
      <div class="item"
           v-for="(itm, inx) in arr"
           :key="inx"
           :tip="itm"
           :style="{height: itm+'px'}"></div>
    </div>
  </div>
</template>

<script>
import Vue from 'Vue'
export default {
  name: 'bubbling',
  data () {
    return {
      arr: []
    }
  },
  mounted () {
    this.buildArray()
  },
  methods: {
    buildArray () {
      for (let i = 0; i < 10; i++) {
        this.arr.push(parseInt(Math.random() * 90 + 10))
      }
      this.beginSort()
    },
    beginSort () {
      let step = 1
      for (let i = 0; i < this.arr.length; i++) {
        for (let j = 0; j < this.arr.length; j++) {
          step++
          setTimeout(() => {
            if (this.arr[i] < this.arr[j]) {
              let temp = this.arr[i]
              /** 方案1 拆装箱
               * this.arr[i] = this.arr[j]
               * this.arr[j] = temp
               * this.arr = JSON.parse(JSON.stringify(this.arr))
               */
               // 方案2 vue.set
              Vue.set(this.arr, i, this.arr[j])
              this.$set(this.arr, j, temp)
            }
          }, step * 200)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.bubbling {
  .report {
    margin: 100px auto;
    display: flex;
    height: 150px;
    width: 460px;
    border-left: 1px solid #666;
    border-bottom: 1px solid #666;
    align-items: flex-end;
    .item {
      width: 40px;
      height: 100px;
      background: #9ee;
      margin-left: 5px;
      text-align: center;
      position: relative;
      transition:all .1s
    }
    .item::before {
      content: attr(tip);
      position: absolute;
      width: 40px;
      height: 20px;
      line-height: 20px;
      left: 0px;
      top: -20px;
      text-align: center;
      font-size: 14px;
      color: #666;
    }
  }
}
</style>

知识点

能触发vue视图更新的方法

push()
pop()
shift()
unshift()
splice() 
sort()
reverse()

无效的

// 直接设置值
this.arr[index] = value;

饮水思源

相关文章

网友评论

      本文标题:Vue数组变化视图不刷新 方案汇总

      本文链接:https://www.haomeiwen.com/subject/hahovctx.html