【问题标题】:Property does not exist on type VueVue 类型不存在属性
【发布时间】:2022-01-07 10:46:50
【问题描述】:

我正在使用 ref 来获取一个值,并且我将“Vue”类型上的属性“值”不存在作为错误。
这是我的代码

  confirmPasswordRules: [
          (v: string ) => !!v || "Password is required",
          (v: string ) => (this.$refs.password) && (v === this.$refs.password.value  || "Passwords do not match")
  ],

我使用 console.log 打印出 this.$refs.password.value 所以它确实有一个值。我还尝试了(this.$refs.password as Vue & { password: () => string }).validate()) 来验证价值,但这没有用。我需要进行哪些更改?

【问题讨论】:

    标签: typescript vue.js ref


    【解决方案1】:

    模板引用的类型为unknown,因此需要将它们类型断言为目标元素的类型。假设模板 ref 位于 <input> 上,则类型断言将为 as HTMLInputElement

    confirmPasswordRules: [
      (v: string) => this.$refs.password && (v === (this.$refs.password as HTMLInputElement).value  || "Passwords do not match")
                                                    ---------------------------------------
                                                                       ?
    ],
    

    【讨论】:

      【解决方案2】:

      计算属性在 onMount 事件之前被解析,这意味着模板部分还没有被渲染并且 refs 没有到位。您可以在触发操作之前检查您的 ref 是否存在。

      (v: string ) => (this.$refs?.password?.value) && (v === this.$refs.password.value  || "Passwords do not match")
      

      【讨论】:

        猜你喜欢
        • 2020-12-18
        • 2021-12-17
        • 2020-12-11
        • 2023-01-03
        • 2019-07-16
        • 2019-03-07
        • 2020-01-14
        • 2021-12-19
        • 2018-01-15
        相关资源
        最近更新 更多