Vue js와 Node js 사용해보기 - 핵심 2
Vue js와 Node js 사용해보기 - 핵심 1 을 이어서 내용을 진행하겠다.
1편 ( https://shlee0882.tistory.com/282?category=797808 )
visual studio code를 실행하여 2개의 파일을 수정할 것이다.
1. src/views/Home.vue
<template> | |
<div class="home"> | |
<hello-world v-bind:name="name" | |
:age="age" | |
:livingArea="livingArea" | |
@change-address="childToParent" | |
> | |
</hello-world> | |
<div><button v-on:click="parentToChild">부모에서 자식으로 주소변경</button></div> | |
<div><button @click="setInitData">원래 주소로 변경</button></div> | |
<div>{{computedName}}</div> | |
</div> | |
</template> | |
<script> | |
import HelloWorld from '@/components/HelloWorld.vue'; | |
export default { | |
components: { | |
'hello-world': HelloWorld, | |
}, | |
data() { | |
return { | |
name: '초기 데이터', | |
age: 999, | |
livingArea: '초기 주소', | |
}; | |
}, | |
computed: { | |
computedName() { | |
return this.name.substring(1, 3); | |
}, | |
}, | |
created() { | |
this.setInitData(); | |
}, | |
methods: { | |
setInitData() { | |
this.name = '이상현'; | |
this.age = 29; | |
this.livingArea = '서울시 송파구'; | |
}, | |
parentToChild() { | |
this.livingArea = '인천광역시 부평구'; | |
}, | |
childToParent(val) { | |
this.livingArea = val; | |
}, | |
}, | |
}; | |
</script> |
[Home.vue]
17라인에 HelloWorld를 다시 21라인에서 hello-world 컴포넌트로 재정의한다.
3라인에 hello-world 태그로 들어가고 HelloWorld.vue 파일에
바인딩 될 데이터를 셋팅해주고 있다
23라인에 초기 데이터를 선언 및 초기화해주고
30라인에서는 계산된 결과값을 가져오고
35라인에서는 뷰가 생성될때 시작되는 함수이다.
2. src/components/HelloWorld.vue
<template> | |
<div class="hello"> | |
<h1>{{ name }}</h1> | |
<h1>{{ age }}</h1> | |
<h1>{{ livingArea }}</h1> | |
<button v-on:click="changeAddress">자식에서 부모로 주소변경</button> | |
</div> | |
</template> | |
<script> | |
export default { | |
name: 'HelloWorld', | |
props: { | |
name: String, | |
age: Number, | |
livingArea: String, | |
}, | |
methods: { | |
changeAddress() { | |
const newAddress = '강원도 속초시'; | |
this.$emit('change-address', newAddress); | |
}, | |
}, | |
}; | |
</script> | |
<!-- Add "scoped" attribute to limit CSS to this component only --> | |
<style scoped> | |
h3 { | |
margin: 40px 0 0; | |
} | |
ul { | |
list-style-type: none; | |
padding: 0; | |
} | |
li { | |
display: inline-block; | |
margin: 0 10px; | |
} | |
a { | |
color: #42b983; | |
} | |
</style> |
[HelloWorld.vue]
13라인 props에서 부모에게 받은 바인딩 된 데이터를 어떻게 받아올지 선언하고
받아온 데이터를 3~5라인에서 출력해주고 있다.
6라인에 changeAddress 클릭 이벤트가 있는데
21라인에 부모의 이벤트를 받는 $emit을 사용해 부모의 change-address를 찾아가 데이터를 전달해준다.
위 두 파일을 수정하여 띄워보면
라우팅에 따라 localhost:8080/, localhost:8080/about 에 다른 페이지가 출력되는 것을 확인 할 수 있다.
위 실습을 통해 Vue js에서 많이 사용하는 아래 항목들에 대해
- data-bind
- on-click
- props
- components
- data()
- computed
- created()
- methods
- $emit
알아 볼 수 있게 되었다.
마지막으로 해당 소스와 배포된 URL을 추가한다.
https://shlee0882.github.io/vuejs-nodejs-basic-setting
https://github.com/shlee0882/vuejs-nodejs-basic-setting