기존 프로젝트에서 axios로 서버와 통신 하기 위해서는 이를 node_modules에 설치해야한다. 이때 다음과 같은 명령어를 사용하면 된다.
npm install axios
이후 /node_modules에 axios가 추가된 것을 확인할 수 있다.
main.js에 axios를 import하고 Vue 인스턴스에 prototype를 이용해 전역선언해서 사용할 수 있다.
json-server는 REST API를 서버를 사용가능하게 하는 라이브러리다. 간단하게 axios통신을 하기 위해서 npm으로 json-server를 다운로드 받아준다.
npm i -g json-server
db.json 만들기
단따옴표 안되고 쌍따옴표로 해야된다.
my-project/json-server 에 가서 서버를 실행시킨다음
json-server --watch db.json
{^_^}/ hi!라니 너무 귀엽잖아 엉엉
localhost:3000으로 url을 접속해보니 임시로 REST API 서버를 확인 할수 있었다(감-동)
db.json을 쓰고싶은 file에 가서
method에 getTodos추가를 해준다
<script>
methods: {
getTodos () {
this.$http.get('http://localhost:3000/arr')
.then((res) => {
// .then(function(res){
console.log('arr:', res.data)
this.exampleItems = res.data
})
}
},
</script>
그리고 mounted 훅을 추가한다
<script>
mounted(){
this.getTodos()
}
</script>
기존에 하드코딩된 data를 삭제하고
data(){
return {
todos:[]
}
},
확인을하면
잘나온다~!
다음엔 수정,삭제,추가를 해봐야겠다