Vue3补充
自定义指令
在 setup 中,任何以 v 开头的驼峰式命名的变量都可以被用作一个自定义指令。在上面的例子中,vFocus 即可以在模板中以 v-focus 的形式使用。
<script setup>
// 在模板中启用 v-focus
const vFocus = {
mounted: (el) => el.focus()
}
</script>
<template>
<input v-focus />
</template>
// 指令钩子
const myDirective = {
// 在绑定元素的 attribute 前
// 或事件监听器应用前调用
created(el, binding, vnode, prevVnode) {
// 下面会介绍各个参数的细节
},
// 在元素被插入到 DOM 前调用
beforeMount(el, binding, vnode, prevVnode) {},
// 在绑定元素的父组件
// 及他自己的所有子节点都挂载完成后调用
mounted(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件更新前调用
beforeUpdate(el, binding, vnode, prevVnode) {},
// 在绑定元素的父组件
// 及他自己的所有子节点都更新后调用
updated(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件卸载前调用
beforeUnmount(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件卸载后调用
unmounted(el, binding, vnode, prevVnode) {}
}
import() 动态导入
当用动态导入的方式导入默认导出时,其工作方式有所不同。你需要从返回的对象中解构并重命名 "default" 键。
(async () => {
if (somethingIsTrue) {
const { default: myDefault, foo, bar } = await import('/modules/my-module.js');
}
})();
getCurrentInstance我有话说
- 需求: 有个child子组件(用setup定义的单文件组件), 需访问父组件上的props属性, 就像使用选项式组件时,可以使用
this.$parent.$props一样
貌似只能在开发环境中可通过getCurrentInstance() 返回值中的 proxy属性拿到当前组件实例; 生产环境中的proxy中没有什么可用信息
✨有没有别的办法?
- 开发环境,截图
- 生产环境截图
TypeScript运动员
将数组每项作为某字段的类型
const triggers = ['hover', 'focus', 'click', 'contextmenu'] as const
type Trigger = typeof triggers[number]
提取enum枚举的value值作为新类型
enum EName {
'李振藩' = 1,
'李小龙' = 2
}
type TKey = keyof typeof EName // "李振藩" | "李小龙"
// type TValue = typeof EName[TKey] // 分两步:(1)先将枚举转为类型 (2)然后将Tkey分配给类型
// 或者这样写
// type TValue = (typeof EName)[TKey] // 分两步:(1)先将枚举转为类型 (2)然后将Tkey分配给类型
type TValue = typeof EName[TKey] // EName
const myname: TValue = 1 // ✅
console.log(EName[myname]) // "李振藩"
const errname: TValue = 3 // ❌ Type '3' is not assignable to type 'TValue'.(2322)
// ==== 封装为一个通用的泛型 ====
type EnumValues<T extends Record<string, any>> = T[keyof T];
type ENameValues = EnumValues<typeof EName>;
function showName(name: ENameValues) {
console.log(name);
}
showName(1); // 1
showName(2); // 2
showName(3); // 报错