嘗試在輸入 1 個字符后自動關注下一個輸入欄位。
出現錯誤:“void”型別上不存在屬性“$refs”。
這是功能:
setup() {
const autoFocusNextInput = (event, max: number) => {
if (event.target.value.length === max) {
const nextElement =
this.$refs[`input-${Number(event.target.dataset.index) 1}`];
if (nextElement) nextElement.focus();
}
};
這是背景關系的模板:
<div class="d-flex flex-wrap justify-content-between">
<Field
class=
type="text"
name="1"
maxlength="1"
ref="input-0"
data-index="0"
@input="autoFocusNextInput($event, 1)"
autocomplete="off"
/>
<Field
class=
type="text"
name="2"
maxlength="1"
ref="input-1"
data-index="1"
@input="autoFocusNextInput($event, 1)"
autocomplete="off"
/>
uj5u.com熱心網友回復:
問題在于箭頭函式語法,箭頭函式沒有定義自己的執行背景關系。this箭頭函式內部的值總是等于this外部函式的值。
Vue 會將this關鍵字系結到實體,以便它始終參考組件實體。因此,在定義方法時確實需要不使用箭頭函式,因為它們總是系結this到父背景關系,這實際上不是 Vue 實體,而是全域物件 ( the Window)。
使用常規函式語法的作業演示:
new Vue({
el:'#app',
methods: {
autoFocusNextInput(event, max) {
if (event.target.value.length === max) {
const nextElement = this.$refs[`input-${Number(event.target.dataset.index) 1}`];
if (nextElement) nextElement.focus();
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
<input
type="text"
name="1"
maxlength="1"
ref="input-0"
data-index="0"
@input="autoFocusNextInput($event, 1)"
autocomplete="off"
/>
<input
type="text"
name="2"
maxlength="1"
ref="input-1"
data-index="1"
@input="autoFocusNextInput($event, 1)"
autocomplete="off"
/>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/442212.html
標籤:javascript html 打字稿 Vue.js Vuejs3
上一篇:方法“getChampionName”在組件定義中具有“未定義”型別。您是否正確參考了該函式?
下一篇:Vuex商店無法訪問
