vue 更新对象数组后无法及时更新视图?

<template>
  <div class="preview">
    <ul>
      <li v-for="(moe,index) in moeList" :key="index">
        <div v-if="moe.loading" class="loading"></div>
      </li>
    </ul>
  </div>
</template>

<script>
import bus from "../eventBus.js";
export default {
  name: "preview",
  data() {
    return {
      moeList: [],
      keyList: [],
    };
  },
  methods: {
    pushMoe(moe){
      let id = moe.id
      if(this.keyList.indexOf(id) === -1){
        this.keyList.push(id)
        moe.loading = true
        this.moeList.push(moe)

        let image = new Image()        
        image.onload = () => {
          console.log(233);
          // this.$set(moe,'loading',false)  // 无效
          moe.loading = false
          this.moeList.push({})
          this.moeList.pop() 
        }
        image.onerror = () => {
          console.log('error');
        }
        image.src = moe.sample_url
      }
    },
  },
  mounted() {
    // this.scroll();
    const self = this;
    bus.$on("pushPreview", moe => self.pushMoe(moe));
  }
};
</script>

如上述代码,使用了this.$set也无法更新视图,请问该怎么办?
目前我是用this.moeList.push({});this.moeList.pop()解决的,有别的办法吗?

阅读 3.6k
2 个回答

data函数里都没有moe这个变量 当然是没用的
你可以用this.$forceUpdate()来强制刷新DOM
也可以this.$set(this.moeList[index],'loading',false)来监测object的变化

pushMoe里面的数组用临时数组接一下,然后将这个临时数组赋值给moreList

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题