我将 Vue 与 TypeScript 和 vue-property-decorator
包一起使用。
当我像这样使用 Prop 时:
@Prop({ default: '' }) private type: string
我得到一个 TS 编译器错误:Property 'type' has no initializer and is not definitely assigned in the constructor.
但是如果我用类似的东西初始化它:
@Prop({ default: '' }) private type: string = ''
然后我在浏览器控制台中收到警告:
vue.runtime.esm.js?ff9b:587 [Vue warn]: Avoid mutating a prop directly since the value will be overwritten
whenever the parent component re-renders. Instead, use a data or computed property based on the prop's
value. Prop being mutated: "type"
那么在这种情况下我应该怎么做才能没有任何错误或警告?
我唯一能想到的是在 tsconfig.json 中设置:"strictPropertyInitialization": false
,但我想尽可能避免这种情况。
谢谢!
最佳答案
初始错误消息是 TypeScript 的严格类初始化(在 2.7 中引入)的结果。 2.7 的发行说明描述了使用 definite assignment operator (!
) 来解决这个问题。在你的情况下,你会这样做:
@Prop({ default: '' }) private type!: string
关于typescript - 为 TypeScript 使用 @Prop 装饰器 - 编译器给出错误要求初始化 prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50422006/