组合 API 中的命名空间
export default {
methods: {
printWidth(name) {
console.log(this.$refs[name].offsetWidth);
}
}
};
以上的使用方式如果在组合 API 中实现,需要一个命名空间。
import { defineComponent, getCurrentInstance} from 'vue';
export default defineComponent({
setup() {
const instance = getCurrentInstance();
const printWidth = (name: string) => {
if (instance) {
// refs的声明为Record<string, unknown>,需要增加断言
console.log((instance.refs[name] as HTMLElement)?.offsetWidth);
}
};
return {printWidth};
}
});
getCurrentInstance 可以在组合 API 中充当 this 的作用。不过,部分属性在生产环境中无法获取,使用时建议参考 vue 的类型声明中 ComponentInternalInstance 的结构。
// 以下属性在生产环境中无法获取
{
ctx: { /* 类似this */},
proxy: { /* 组件的响应性数据 */},
devtoolsRawSetupState: { /* setup 中 return的变量 */ }
}
watch
- watch 多个数据源 多个数据源可拼入数组作为 watch 参数。
watch(
[data1, data2],
([data1, data2], [preData1, preData2]) => {
console.log(data1, data2);
}
);
- watch 数组和对象 对象和数组如果需要 watch 内部变更需要添加 deep 参数。
const arr = ref<string[]>([]);
watch(
arr,
(value, preValue) => {
console.log(value, preValue);
},
{deep: true}
);
- watch dom 注意! 由于 watch 在更新前执行,而更新的 dom 在更新后才可获取,watch到的变化将延迟一轮渲染。
setup() {
cosnt element = ref<HTMLElement|null>(null);
watch(element, (value, preValue) => {
if (value && !oldValue) {
console.log('show');
}
else if (!value && oldValue) {
console.log('hidden');
}
});
return {element};
}
PropType
复杂类型的 prop 在组件内默认的类型推断经常与我们期望的结构不一致,PropType 可以为 prop 提供全面的类型断言。
import { defineComponent, PropType} from 'vue';
export default defineComponent({
props: {
info1: {
type: Object,
required: false,
default: () => ({})
},
info2: {
type: Object as PropType<{ age: number}>,
required: false,
default: () => ({age: 0})
}
},
setup(props) {
props.info1 // Record<string, any>
props.info2 // { age: number}
}
});
学习过程中也产生了一些疑问
- 如何对组件间传参做ts类型校验?
- 如何『同步』watch dom?