개발

[Vue] ref로 input에 focus

yun000 2025. 3. 7. 15:38

기대 효과

input에 focus를 주어서

내용을 입력할 수 있도록 커서가 깜빡이는 상태로 변환.


코드

input에 ref 지정

<input type="number" ref="myInput" v-model="num">

input에 focus

this.$refs.myInput.focus();

예제

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>


<body>
    <div id="app">
        <input type="number" ref="myInput" v-model="num">
        <button v-on:click="onClickBtn">button</button>
    </div>
</body>


<script>
    const app=new Vue({
        el:'#app',
        data:{
            num:'',
        },
        methods:{
            onClickBtn(){
                this.num='';
                this.$refs.myInput.focus();
            }
        }
    });
</script>
</html>