<input>에 입력한 데이터는 무조건 문자입니다.'123'으로 저장됩니다.v-model.number="데이터이름"을 사용합니다.'abc'와 같은 문자를 막을 순 없습니다.watch 옵션(또는 Composition API의 watch 함수)을 사용해 특정 데이터를 감시합니다.<script setup>에서의 Watcher 사용 예제원래 Vue2 코드:
export default {
data(){
return {
month : 1
}
},
watch : {
month(){
// month가 변경될 때 실행할 코드
}
}
}
Vue3 <script setup>으로 리팩토링:
<script setup>
import { ref, watch } from 'vue'
const month = ref(1)
watch(month, (newVal, oldVal) => {
// month가 변경될 때 실행할 코드
})
</script>
원래 Vue2 코드:
export default {
data(){
return {
month : 1
}
},
watch : {
month(a){
if (a > 12) {
alert('13이상 입력하지마')
}
}
}
}
Vue3 <script setup>으로 리팩토링:
<script setup>
import { ref, watch } from 'vue'
const month = ref(1)
watch(month, (newVal, oldVal) => {
if (newVal > 12) {
alert('13이상 입력하지마')
}
})
</script>
watch 옵션이나 함수에 감시할 데이터를 인자로 넣어주면, 해당 데이터가 변경될 때마다 등록한 콜백 함수가 실행됩니다.