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
Author And Source
この問題について(vue-property-decoratorでrefを使ったDOM操作がうまくできない), 我々は、より多くの情報をここで見つけました https://qiita.com/abetomohiro/items/0f167e37822287125db1著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .