我目前正在使用 TS 使用这些库进行组件设置的 Vue 2 项目:vue-class-component
和 vue-property-decorator
我需要创建一个表单组件,但是我很难处理数据绑定(bind),因为当我为表单组件使用 data() 选项时,它会在编译时产生错误。
有没有办法在不使用 data() 选项的情况下绑定(bind)输入数据?
我得到的错误:
ERROR in /path/to/components/folder/Form.vue
Property 'id' does not exist in type 'Form'.
有关更多上下文,这是我的代码:@Component
export default class Form extends Vue {
//Bind form data
data() {
return {
id: "",
name: "",
age: 0,
amountA: 0,
amountB: 0,
capitalA: 0,
capitalB: 0
}
}
onSubmit(e: any): void {
e.preventDefault();
//Create new class object
const newClass = {
id: this.id,
name: this.name,
age: this.age,
amountA: this.amountA,
amountB: this.amountB,
capitalA: this.capitalA,
capitalB: this.capitalB
}
//Emit the class object to parent component
this.$emit("add-class", newClass);
this.$emit("update-total");
//Reset Form
this.id = ""
this.name = ""
this.age = 0
this.amountA = 0
this.amountB = 0
this.capitalA = 0
this.capitalB = 0
}
这是我控制台上的错误:Console error任何人都可以帮助我解决这些错误。谢谢!
最佳答案
在 Vue 类组件装饰器中,Options API 的 data()
函数被抽象掉了。@Component
decorator 是一个负责将代码从 Class API 语法转换为 Options API 语法的函数。
即,在幕后:
data()
react 性 Prop ,computed
Prop methods
. 所以只需在类实例上直接声明 Prop :
@Component
export default class Form extends Vue {
id = "";
name = "";
age = 0;
amountA = 0;
amountB = 0;
capitalA = 0;
capitalB = 0;
// props declared above are reactive and you can now use them
// in getters or methods
}
参见 Overview 中的示例页。更详细地说,这个特定的评论:// Class properties will be component data
警告:如果您刚刚开始使用 Vue,请注意 Vue 类装饰器语法的使用趋势正在下降,并且 Vue 3 兼容性问题是可以预料的(并且已经开始浮出水面)。看看他们 repo 的未解决问题。
同样,您可能想阅读 this comment作者:尤文 1 , ref Vue 类组件装饰器的用法:
It definitely isn't a recommended option anymore in official docs or default tooling (moving to Vite-based soon and vue-cli will be in maintenance mode).
Deprecation will depend on actual usage and @ktsn's2 intention on further working on the project.
1 ::Vue的作者
2 ::
vue-class-component
的维护者包裹个人建议:安装@vue/composition-api在你的 Vue 2 项目中,用 Composition API 语法重写它的组件比用类装饰器语法编写对你自己和项目都更有益。
在执行此操作时,您将
由于类装饰器语法的流行度正在下降,随着时间的推移,对它的支持可能会变得更加难以获得。
如果在 Composition API 中重写现有组件不是一种选择,您至少可以使用这种语法编写新组件,因为该语法是逐渐可采用的,它可以与任何其他有效的 Vue API 语法一起使用。
关于javascript - Vue JS - vue-class-component 绑定(bind)输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70735541/