캡틴판교 장기효님의 Vue.js시작하기 인프런 강의를 수강하고 내용을 정리했다.
매일 20분 야금야금 Vue.js 고생했다.(2021년 9월 26일~ 10월19일) 이제 복습하자.
IDE: Visual Studio Code
크롬 뷰 개발자 도구: Vue.js devtools
[Vue.js 시작하기]기본강의의 마지막 파트다.
Vue CLI 로 프로젝트를 생성해서 '사용자 입력 폼'을 만들어보자.
터미널을 하나 열어서 vue-form 이름의 프로젝트를 생성한다.
vue create vue-form
Defalut [vue 2]를 선택하자.
$ cd vue-form
$ npm run serve
뷰를 실행하고, 브라우저에서 개발자도구 뷰를 켜고 정상적으로 App 컴포넌트가 만들어지는지 확인하자.
App.vue의 내용을 지우고, 아래처럼 새로 작성하자.
<template>
<div>
hi
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
기본 생성된 /src/components/HelloWorld.vue 컴포넌트는 삭제하자.
<template>
<form action="">
<div>
<label for="username">id: </label>
<input id="username" type="text">
</div>
<div>
<label for="password">pw: </label>
<input id="password" type="password">
</div>
<button>login</button>
</form>
</template>
<script>
export default {
}
</script>
<style>
</style>
App.vue에 데이터를 정의하여 input 박스에 입력된 값을 뷰 data로 받자.
<script>
export default {
data: function(){
return {
username: '',
password: ''
}
}
}
</script>
컴포넌트 간에 데이터참조가 겹치지 않게 data는 function() return{} 형태로 써야한다.
input에 값을 입력하면 즉시 뷰 데이터에 바인딩 됨을 개발자도구에서 확인할 수 있다.
<template>
<form action="">
<div>
<label for="username">id: </label>
<input id="username" type="text" v-model="username">
</div>
<div>
<label for="password">pw: </label>
<input id="password" type="password" v-model="password">
</div>
<button>login</button>
</form>
</template>
<script>
export default {
data: function(){
return {
username: '',
password: ''
}
}
}
</script>
버튼 type을 submit으로 만들면 form을 제출 시킨다.
form이 제출(submit)되면 기본적으로 '새고로침'된다.
v-on:submit 속성을 form태그에 작성하여 제출 시 실행되는 메서드 명을 적어준다
<form v-on:submit="submitForm">
<div>id...</div>
<div>pw ...</div>
<button type="submit">login</button>
</form>
id, pw에 값을 넣고 버튼을 클릭해보자. 콘솔에 id, pw가 출력된다.
<script>
export default {
data: function(){
return {
username: '',
password: ''
}
},
methods:{
submitForm: function(){
console.log(this.username, this.password);
}
}
}
</script>
폼을 제출하고 다음 페이지로 넘어가는 특징이 있다.
event.preventDefault() 로 기본적인 새로고침을 방지하자.
methods:{
submitForm: function(event){
event.preventDefault();
console.log(this.username, this.password);
}
}
v-on디렉티브에 prevent를 덧붙이면 새로고침을 방지할 수 있다.
<form v-on:submit.prevent="submitForm">
이벤트가 전달되는것과 이벤트가 어느 방향으로 흐르는지 이해하자
axios라는 모듈을 현재 프로젝트에 install 한다.
npm i axios
export default 위에 import 를 적어준다.
import axios from 'axios';
axios : 웹서버 간에 데이터를 주고받기 위한 HTTP 라이브러리
아래 URL은 RESTapi 에 따라 데이터를 보내고 결과를 받을 수 있다.
var url = 'https://jsonplaceholder.typicode.com/users';
post()에 url과 data를 넘긴다.
methods:{
submitForm: function(){
var url = 'https://jsonplaceholder.typicode.com/users';
var data = {
username: this.username,
password: this.password
}
axios.post(url, data);
console.log(this.username, this.password);
}
}
post가 성공했을 때의 응답을 then()함수 내에서 response 파라미터 출력으로 확인한다.
post가 실패했을 때 에러 내용을 catch() 함수 내에서 error 파라미터 출력으로 확인한다.
methods:{
submitForm: function(){
console.log(this.username, this.password);
var url = 'https://jsonplaceholder.typicode.com/users';
var data = {
username: this.username,
password: this.password
}
axios.post(url, data)
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
})
}
}
<template>
<form v-on:submit.prevent="submitForm">
<div>
<label for="username">id: </label>
<input id="username" type="text" v-model="username">
</div>
<div>
<label for="password">pw: </label>
<input id="password" type="password" v-model="password">
</div>
<button type="submit">login</button>
</form>
</template>
<script>
import axios from 'axios';
export default {
data: function(){
return {
username: '',
password: ''
}
},
methods:{
submitForm: function(){
console.log(this.username, this.password);
var url = 'https://jsonplaceholder.typicode.com/users';
var data = {
username: this.username,
password: this.password
}
axios.post(url, data)
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
})
}
}
}
</script>
<style>
</style>
자주 업데이트가 되는데 번역이 이것을 따라가기 힘들다.
원문을 보는 것을 권한다.
코드 작성 스타일 정독을 추천합니다
실제 구현 할 때 부딪힐 법한 실용적인 문법이나 고민들이 글로 정리되어 있다.
공식문서를 읽으면서 구현까지 해보시면 머리에 많이 남으실 것입니다.
다음 중급 강의도 화이팅 😊