15
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【TypeScript + Vue】$refsを使った子コンポーネントのアクセスでエラーになったとき

Posted at

エラー内容

Property 'hello' does not exist on type 'Vue | Element | Vue[] | Element[]'.
Property 'hello' does not exist on type 'Vue'.Vetur(2339)

helloなどというプロパティが"Vue"型には存在しませぬぞ!
と言われております。

コード

親コンポーネント

Parent.vue
<template>
  <clild ref="clildGreet" />
</template>

<scirpt lang="ts">
  import Vue from "vue";
  import Component from "vue-class-component";
  import Child from "./Child.vue";

  @Component({
    name: "parent",
    components: { Child }
  })
  export default class Parent extends Vue {
    created() {
      // 子コンポーネントのhelloというメソッドを呼び出したい。
      this.$refs.clildGreet.hello();
    }
  }
</script>

子コンポーネント

Child.vue
<template>
  <p>{{text}}</p>
</template>

<scirpt lang="ts">
  import Vue from "vue";
  import Component from "vue-class-component";

  @Component({
    name: "child"
  })
  export default class Child extends Vue {
    text:string = "";

    hello() {
      this.text = "hello";
    }
  }
</script>

解決策

親コンポーネント

Parent.vue
<template>
  <clild ref="clildGreet" />
</template>

<scirpt lang="ts">
  import Vue from "vue";
  import Component from "vue-class-component";
  import Child from "./Child.vue";

  @Component({
    name: "parent",
    components: { Child }
  })
  export default class Parent extends Vue {
    get refs():any {
      return this.$refs;
    }

    created() {
      // 子コンポーネントのhelloというメソッドを呼び出したい。
      this.refs().clildGreet.hello();
    }
  }
</script>

this.$refsに型anyを付けてあげることで回避。

15
8
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?