a minute ago

Vue.jsの「this.$refs.xxx」がTypeScriptに怒られる。TS2339: Property 'xxx' does not exist on type 'Vue | Element | Vue[] | Element[]'


TS2339: Property 'xxx' does not exist on type 'Vue | Element | Vue[] | Element[]'.   Property 'xxx' does not exist on type 'Vue'.

解決策

asを使う

<template>  
    <sample-component ref="sampleInput"></sample-component>
</template>
<script lang="ts">
import { Component, Vue } from 'nuxt-property-decorator'
import SampleComponent from '@/components/SampleComponent.vue'

@Component({
  components: {
    SampleComponent,
  }
})
export default class Parent extends Vue {
  $refs!: {
    sampleInput: SampleComponent
  }
  
    mounted () {
    const inputElm = this.$refs.sampleInput as SampleComponent
    this.$refs.sampleInput.sampleData = 'sample'
  }
}
</script>

$refsを上書きする

<template>
    <sample-component ref="sampleInput"></sample-component>
</template>
<script lang="ts">
import { Component, Vue } from 'nuxt-property-decorator'
import SampleComponent from '@/components/SampleComponent.vue'

@Component({
  components: {
    SampleComponent,
  }
})
export default class Parent extends Vue {
  $refs!: {
    sampleInput: SampleComponent
  }
  
    mounted (): void {
    this.$refs.sampleInput.sampleData = 'sample'
  }
}
</script>

asは最終手段な感があるので後者がいいのかなと思いました。


Related Articles