vue: 解决页面数据不渲染问题

一、this.$forceUpdate()

原理:

// 作用:迫使 Vue 实例重新渲染。注意它仅仅影响实例本身和插入插槽内容的子组件,而不是所有子组件。
// 实例需要重新渲染是在依赖发生变化的时候会通知watcher,然后通知watcher来调用update方法,就是这么简单。
Vue.prototype.$forceUpdate = function () {
    const vm: Component = this
    if (vm._watcher) {
        vm._watcher.update()
    }
}

实例:

getAddress () {
  this.data.forEach(item => {
     if (item.id === this.value) {
       this.addressInfo = item
     }
   })
  this.$forceUpdate()
},

二、this.$set()

dialogFormData: {
        logoUrl: '',
        logoCode: '',
      },

直接赋值不能渲染,

$set方法解决:

toRequest(data) {
      // 发起请求
      const fd = new FormData();
      fd.append('file', data.file);
      this.$axios({
        method: 'post',
        url: fileUpload,
        headers: { 'Content-Type': 'multipart/form-data' },
        data: fd,
      }).then((res) => {
        this.$set(this.dialogFormData,'logoUrl',res.data.payload)
        this.$message({ type: 'success', message: '上传成功' });
      });
    },

可以了:

三、:key

相当于每次都是用了新组件,解决了渲染问题

在data里定义key

// 在data里边定义key
key: new Date().getTime()
// 在组件里边使用key
<formPicker
    v-if="form.effectiveness === '否'"
    title="结束时间"
    type="date"
    :key="key"
    :value="form.endDate"
    :minDate="minDate"
    :maxDate="maxDate"
    :required="true"
    placeholder="请选择有效期结束时间"
    @onConfirm="onConfirm($event,'end')">
</formPicker>

四、setTimeout()

// 方法
export function sleep (time) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, time)
  })
}
// 引入
import { formatTime, sleep } from '@/utils/index'
// 使用
sleep(500)

 五、this.$nexttick(()=>{})

handleSelectionChange(selection,row) {
      this.$refs.singleTable.$refs.table.clearSelection()
      if (row) {
        this.$nextTick(() => {
          this.$refs.singleTable.$refs.table.toggleRowSelection(row, true)
        })
      }
      this.$emit('selection', row)
    },

六、watch(相关内容)

监听数据变化

watch: {
    "$route.path"(path) {
      this.active = path;
    }
  },
watch: {
    '$store.state.tab.currentPath'(tab) {
      this.tabName = tab.pathname;
      this.$router.push(tab.pathname);
    },
    positionList: {
      handler: function (val, oldVal) {
        this.positionListInfo = val;
        this.positionInfo = this.positionTitle;
      },
      deep: true,
    },
    activeIndex: function (val, oldVal) {
      //监听vuex中activeIndex值
      if (!this.isNavClick) {
        this.topNavData();
      }
    },
  },
watch: {
    activeIndex: {
      immediate: true,
      handler(val) {
        this.tabsActiveIndex = val;
      },
    },
  },

七、computed(相关内容)

计算属性

computed: {
   searchData () {
     return this.showCollapse && this.collapse ? this.compactData : this.data
   }
},
computed: {
  isViewMode () {
    return this.imgAttr.disabled
  }
},

 八、参考连接

深入响应式原理 — Vue.js (vuejs.org)

(13条消息) Vue中,$forceUpdate()的使用_y521123y的博客-CSDN博客_$forceupdate

九、欢迎交流指正

猜你喜欢

转载自blog.csdn.net/snowball_li/article/details/120338534