【问题标题】:Vue JS - vue-class-component binding inputVue JS - vue-class-component 绑定输入
【发布时间】:2022-01-17 01:13:29
【问题描述】:

我目前正在使用 TS 开发一个 Vue 2 项目,使用这些库进行组件设置:vue-class-componentvue-property-decorator

我需要创建一个表单组件,但我很难进行数据绑定,因为当我为表单组件使用 data() 选项时,它会在编译时产生错误。

有没有办法在不使用 data() 选项的情况下绑定输入数据?

我得到的错误:

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

谁能帮我解决这些错误。谢谢!

【问题讨论】:

    标签: javascript typescript vue.js vuejs2


    【解决方案1】:

    在 Vue 类组件装饰器中,Options API 的 data() 函数被抽象掉了。

    @Component 装饰器是一个函数,负责将您的代码从 Class API 语法转换为 Options API 语法。

    即幕后:

    • 所有类道具都变成data()反应道具,
    • 所有的getter/setter都变成computedprops
    • 所有类方法(正则函数)都变成methods

    所以直接在类实例上声明 props:

    @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 页面中的示例。更详细地说,这个特定的评论:

    // 类属性将是组件数据


    警告:如果您刚刚开始使用 Vue,请注意 Vue 类装饰器语法的使用趋势正在下降,并且 Vue 3 兼容性问题是可以预料的(并且已经开始浮出水面) )。看看他们 repo 上的未解决问题。

    同样,您可能想阅读 Evan You 的 this comment1,参考 Vue 类组件装饰器的用法:

    在官方文档或默认工具中绝对不再是推荐的选项(很快就会迁移到基于 Vite 并且 vue-cli 将处于维护模式)。
    弃用将取决于实际使用情况和@ktsn2对项目进一步开展工作的意图。

    1 :: Vue 的作者
    2 :: vue-class-component 包的维护者


    个人建议:在您的 Vue 2 项目中安装 @vue/composition-api 并使用 Composition API 语法重写其组件比编写类装饰器语法对您自己和项目都更有益。

    这样做,你会

    • 使项目可以相对轻松地升级到 Vue 3

    由于类装饰器语法的流行度正在下降,随着时间的推移,对它的支持可能会变得更加难以获得。

    如果在 Composition API 中重写现有组件不是一种选择,您至少可以使用这种语法编写新组件,因为该语法是逐渐可采用的,它可以与任何其他有效的 Vue API 语法一起使用。

    【讨论】:

    • 您好,首先感谢您赐教!我一定会更仔细、更深入地研究这个话题。我真的很感谢所有的细节和解释。最后,我确实重构了我的代码,它工作得非常好,就像你说的我一直在混合 vue 常规方式和 vue 组件方式。
    猜你喜欢
    • 2021-07-03
    • 1970-01-01
    • 2023-03-30
    • 2018-01-10
    • 2019-10-20
    • 2018-04-06
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    相关资源
    最近更新 更多