vue3中使用nextTick和forceUpdate+vue3 ts使用EventBus

一、 vue中使用forceUpdate

作用:在Vue官方文档中指出,$forceUpdate具有强制刷新的作用,迫使vue实例重新(rander)渲染虚拟dom,注意它仅仅影响实例本身和插入插槽内容的子组件,而不是所有子组件。

vue2中使用

this.$forceUpdate()

vue3中使用

import { getCurrentInstance } from 'vue' // 先引入
setup(){
// 解构赋值 设置别名that,也可不写:that,直接ctx
      let { ctx: that } = getCurrentInstance()
    that.$forceUpdate()
}

这样使用的时候会报错 Property ‘ctx’ does not exist on type ‘ComponentInternalInstance | null’.

类型检测

const { ctx: that } = getCurrentInstance() as any

二、vue中使用$nextTick

作用:vue中的nextTick()是在下次 DOM 更新循环结束之后执行延迟回调,在修改数据之后使用$nextTick(),则可以在回调中获取更新后的 DOM。

在vue2中使用

this.visible = false
// 直接使用
this.$nextTick(() => {
   // 要执行的方法
    this.visible = true
})

在vue3中使用

import { nextTick } from 'vue' // 先引入
setup () {
    const visible = ref<boolean>(false)
    // 使用
    nextTick(()=>{
        visible.value = true
    })
    return {
        visible
    }
}

vue3利用ts使用EventBus

/**
 * 简易的发布订阅模式
 * 主要用于跨组件通信
 */
class EventBus {
  static list: { [key: string]: Array<Function> } = {};

  // 订阅
  static listen(name: EventTypeName, fn: Function) {
    this.list[name] = this.list[name] || [];
    this.list[name].push(fn);
  }

  // 发布
  static notify(name: EventTypeName, data?: any) {
    if (this.list[name]) {
      this.list[name].forEach((fn: Function) => {
        fn(data);
      });
    }
  }

  // 取消订阅
  static unListen(name: EventTypeName) {
    if (this.list[name]) {
      // delete this.list[name];
      Reflect.deleteProperty(this.list, name);
    }
  }

   // 只使用一次
    // static once(name: EventTypeName, fn: Function) {
    //  const _this = this
    //  const wrapper = function () {
    //    fn.apply(this, [arguments])
     //   _this.unListen(name, wrapper)
     // }
     // this.notify(eventName, wrapper)
   // }
}
export default EventBus;

/**
 * 用于规范统一命名,减少名称不一致导致的错误
 */
export enum EventTypeName {
  // 打开报告
  OPEN_REPORT,
  // 打开
  OPEN,
}

  EventBus.listen(EventTypeName.OPEN_REPORT, (data: any) => {
    console.log('data :>> ', data);
    let lti48Obj: any = {
      1: "inspection", // 检验
      2: "microorganism", //微生物
      99: "check", // 检查
    };
    state.reportId = data.reportId; // 报告id
    state.defaultValue = lti48Obj[data.lti48];
  });
EventBus.notify(EventTypeName.OPEN_REPORT, row)
或者
EventBus.listen(EventTypeName.OPEN_REPORT, (data: Function) => {
  data(row)
});
EventBus.notify(EventTypeName.OPEN_REPORT, (data: any) => {
    let lti48Obj: any = {
      1: "inspection", // 检验
      2: "microorganism", //微生物
      99: "check", // 检查
    };
    state.reportId = data.reportId
    state.defaultValue = lti48Obj[data.lti48]
  });

//销毁EventBus
 onUnmounted(() => {
   EventBus.unListen(EventTypeName.OPEN_REPORT);
 });

猜你喜欢

转载自blog.csdn.net/irisMoon06/article/details/129354993