属性 Vue 类型不存在

Property does not exist on type Vue

我正在使用 ref 获取一个值,但我收到 属性 'value' does not exist on type 'Vue' 作为错误。
这是我的代码

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

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

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

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

模板引用的类型为 unknown,因此需要将它们声明为目标元素的类型。假设模板引用在 <input> 上,类型断言将是 as HTMLInputElement:

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