vue3怎么像vue2一样使用typescript?
在vue2里面使用typescript,可以这么写:
export default class App extends Vue {
created(): void {
this.setWindowSize();
}
mounted(): void {
let waitForResizeEndTimer: null | number = null;
window.onresize = () => {
const waitTime = 500;
if (waitForResizeEndTimer === null) {
waitForResizeEndTimer = window.setTimeout(() => {
this.setWindowSize();
}, waitTime);
} else {
clearTimeout(waitForResizeEndTimer);
waitForResizeEndTimer = window.setTimeout(() => {
this.setWindowSize();
}, waitTime);
}
};
}
//普通的method
async test():void{
//code
}
//store里面的action
@Action('setScreenType')
private setWindowSize!: SetScreenTypeAction;
@State('language')
private language!: string;
//computed属性,实时获取store数据
private get currentLang(): string {
return this.language;
}
//监听store数据变化
@Watch('currentLang', { immediate: true })
private onChangeCurrentLang(/*newVal: string, oldVal: string*/) {
console.log(this.currentLang);
}
//定义一个data
private username= 'string-data';
//监听data变化
@Watch('username')
private onChangeUsername(/*newVal: string, oldVal: string*/) {
console.log(this.username);
}
}
这个写法组件之间js部分可以直接使用class的继承,如果封装得当,这一点可以省去很多重复代码,可是在vue3中使用typescript,我想要使用setup,只能这么写,使用defineComponent定义一个object结构:
export default defineComponent({
setup: (): { language: Ref<SupportLanguageType> } => {
const store: Store<RootState> = useStore();
console.log(store);
const language = ref(store.state.language);
watch(language, () => {
console.log(language);
});
return {
language
};
},
created(): void {
const store: Store<RootState> = useStore();
store.dispatch('setScreenType');
// this.setWindowSize();
}
});
要是vue3想像vue2一样,使用class定义,那就要这么写:
export default class App extends Vue {
setup(): { language: Ref<SupportLanguageType> } {
const store: Store<RootState> = useStore();
console.log(store);
const language = ref(store.state.language);
watch(language, () => {
console.log(language);
});
return {
language
};
}
created(): void {
this.setWindowSize();
}
mounted(): void {
let waitForResizeEndTimer: null | number = null;
window.onresize = () => {
const waitTime = 500;
if (waitForResizeEndTimer === null) {
waitForResizeEndTimer = window.setTimeout(() => {
this.setWindowSize();
}, waitTime);
} else {
clearTimeout(waitForResizeEndTimer);
waitForResizeEndTimer = window.setTimeout(() => {
this.setWindowSize();
}, waitTime);
}
};
}
@Action('setScreenType')
private setWindowSize!: SetScreenTypeAction;
@State('language')
private language!: string;
private get currentLang(): string {
return this.language;
}
}
这时候setup就不起作用,感觉使用defineComponent完全限制了typescript的灵活度,也不能让组件之间作为class可继承的优势,有没有二者都可兼得的写法?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
class方案被弃用了,跟着官方走吧