0
0

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 3 years have passed since last update.

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

Last updated at Posted at 2021-09-20

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

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?