vue-property-decoratorでrefを使ったDOM操作がうまくできない


vue2 + typescriptでは$refsがうまく動かないことがあるので
vue-property-decorator の@Refを使うと良いらしいけど
時々refの値が取れないことがある。

component.vue
<template>
    <div class="row">
        <div class="col">
            <input type="text" ref="textbox" v-model="title" />
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Ref, Vue } from 'vue-property-decorator';

@Component
    export default class Hoge extends Vue {

        @Ref('textbox') readonly textbox!: HTMLInputElement;

        created() {
                          // ref操作
             this.textbox.focus();          
        }
    }
</script>

この場合this.textbox が undefindやんけてエラーが出る。

"TypeError: Cannot read properties of undefined (reading 'focus')"

対処方法はsetTimeoutとかthis.$nextTickとか使ってちょっと実行タイミングをずらして操作することらしい。

vue.js
// ref操作
this.$nextTick(() => this.textbox.focus());

なんやそれ(・ω・`

参考
https://stackoverflow.com/questions/60174338/vuejs-typescript-class-component-refs-focus-not-working