vue3中使用nextTick和forceUpdate+vue3 ts使用EventBus
vue
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
项目地址:https://gitcode.com/gh_mirrors/vu/vue

·
一、 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);
});




vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:7 个月前 )
9e887079
[skip ci] 6 个月前
73486cb5
* chore: fix link broken
Signed-off-by: snoppy <michaleli@foxmail.com>
* Update packages/template-compiler/README.md [skip ci]
---------
Signed-off-by: snoppy <michaleli@foxmail.com>
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 9 个月前
更多推荐
所有评论(0)