Vue: 버튼 클릭 시 .focus()를 호출하는 방법
나는 단지 코딩을 시작했을 뿐이다.vue.js
어제, 그리고 '전통적인' JS 방식을 쓰지 않고 텍스트 박스에 '집중'하는 방법을 모르겠다.document.getElementById('myTextBox').focus()
.
처음에 내 텍스트 상자는 숨겨져 있다.시작 단추가 있는데 사용자가 클릭하면 텍스트 상자가 표시되고focus
말하자면 거기다나는 이미 사용해 보았다.ref
, 그러나 소용이 없었다(아래 코드 참조).
HTML:
<input id="typeBox" ref="typeBox" placeholder="Type here..." />
자바스크립트
export default {
name: 'game',
methods: {
startTimer () {
setTimeout(function () { /* .focus() won't work without this */
/* ugly and not recommended */
// document.getElementById('typeBox').focus()
/* Throws the error: Cannot read property 'typeBox' of undefined */
this.$refs.typeBox.focus()
// ... any other options?
// ...
}, 1)
}
} /* END methods */
} /* END export default */
이거 할 줄 아는 사람 있어?제발 도와주세요.
업데이트:
추가autofocus
에 관하여input
페이지가 로드된 직후에 집중하는 요령하지만 내 앱에서는 페이지를 다시 로드하지 않고 입력란에 여러 번 '리포커스(refocus)'할 필요가 있어 전화할 수 있는 방법이 필요하다..focus()
.
누군가 같은 문제에 부딪힐 경우를 대비해서 여기서 해결책을 공유하는 것...
나는 수석 프로그래머의 도움으로 마침내 이것을 알아냈다.나 역시도 제거할 수 있었다.setTimeout
그 길을 따라, 그 길을 가다.vue
버전nextTick()
.
올바른 JS 코드:
startTimer () {
this.$nextTick(() => {
// this won't work because `this.$refs.typeBox` returns an array
// this.$refs.typeBox.focus()
//this one works perfectly
this.$refs.typeBox[0].focus()
})
} /* END startTimer */
설명:
사용할 때console.log(this.$refs.typeBox)
, 이 배열을 반환함:
그렇기 때문에 코드가 작동되려면 그렇게 해야 했다.typeBox[0].focus()
대신에typeBox.focus()
.
의 가치this
에서setTimeout
기능이 로 설정될 것이다window
일정 기간 후에 실행된 콜백 함수인데다 그 범위를 잃었기 때문에 객체this
함수가 호출되는 위치에서 동적으로 설정된 키워드.
화살표 함수가 의 고유한 값을 바인딩하지 않음this
.
startTimer () {
setTimeout(() => {
this.$refs.typeBox.focus()
}, 1)
}
OR
startTimer () {
const self = this;
setTimeout(function () {
self.$refs.typeBox.focus()
}, 1)
}
마침내 문제없이 해결했다.setTimeout
덕분에.window.requestAnimationFrame
(이유를 모르겠다):
startTimer () {
window.requestAnimationFrame(() => this.$refs.typeBox.focus())
}
맞춤 구성 요소 포커스를 맞춰도 작동한다.
참조URL: https://stackoverflow.com/questions/42695728/vue-how-to-call-focus-on-button-click
'programing' 카테고리의 다른 글
Vue js 어레이로 문자열을 분할하고 목록 렌더러에서 사용하는 방법 (0) | 2022.04.25 |
---|---|
일반 클래스의 정적 메서드? (0) | 2022.04.24 |
Mocha 및 Chai를 사용하여 Vuex 모듈을 테스트하는 방법 (0) | 2022.04.24 |
Android - SPAN_EXBLEX_EXBLEX 스팬의 길이는 0일 수 없음 (0) | 2022.04.24 |
상태 액세스 시 알 수 없는 돌연변이 유형 (0) | 2022.04.24 |