[Vue.js] 싱글파일 컴포넌트에 배운 내용 적용하여 개발 시작하기

2021. 9. 26. 22:36개발공부/Vue.js 시작하기

싱글파일 컴포넌트에 배운 내용 적용하여 개발 시작하기


<template>
  <div>
    hi
  </div>
</template>

<script>
export default {
  data: function() {
    return {

    }
  }
}
</script>

<style>

</style>

싱글 컴포넌트 파일을 쓰는 경우 data: function() 형식으로 data를 선언해줘야 합니다.

다른 컴포넌트를 import 하는 방법을 알아보겠습니다.

<template>
  <div>
    {{ str }}
    <app-header></app-header>
  </div>
</template>

<script>
import AppHeader from './components/AppHeader.vue'

var AppHeader = {
  template: '<header><h1>Header</h1></header>'
}

export default {
  data: function() {
    return {
      str: 'hello world'
    }
  },
  components: {
    'app-header': AppHeader
  }
}
</script>

<style>

</style>

//AppHeader.vue
<template>
    <header>
        <h1>Header</h1>
    </header>
</template>

<script>
    export default {

}
</script>

<style>

</style>

기본 강의에선 var AppHeader라는 인스턴스에 template을 설정해줬는데 앞으론 import에 컴포넌트 name과 경로를 작성해줘서 사용해줍니다.

props를 적용하는 방식도 유사합니다. props는 상위 컴포넌트의 데이터를 하위 컴포넌트가 사용할 수 있도록 vue의 reactivity 원리를 사용한 속성입니다.

<template>
    <div>
        <app-header v-bind:propsdata="str"></app-header>
    </div>
</template>

<script>
    import AppHeader from './components/AppHeader.vue'

    export default {
    data: function() {
    return {
    str: 'Hello world'
}
},
    components: {
    'app-header': AppHeader
}
}
</script>

<style>

</style>

// AppHeader.vue
<template>
  <header>
      <h1>{{ propsdata }}</h1>
  </header>
</template>

<script>
export default {
    props: ['propsdata']
}
</script>

<style>

</style>

하위 컴포넌트인 AppHeader.vue에 props를 선언해주고 상위 컴포넌트에서 v-bind:를 사용해 바인딩해 데이터를 넘겨줍니다.

상위 컴포넌트에 이벤트를 전달해 메서드를 실행시킬 수 있게 해주는 코드도 같은 원리입니다.


<template>
    <div>
        <app-header
            v-bind:propsdata="str"
            v-on:renew="renewStr"></app-header>
    </div>
</template>

<script>
    import AppHeader from './components/AppHeader.vue'

    export default {
    data: function() {
    return {
    str: 'Hello world'
}
},
    methods: {
    renewStr: function() {
    this.str = 'whole new world';
}
},
    components: {
    'app-header': AppHeader
}
}
</script>

<style>

</style>


//AppHeader.vue
<template>
  <header>
      <h1>{{ propsdata }}</h1>
      <button v-on:click="sendEvent">send</button>
  </header>
</template>

<script>
export default {
    props: ['propsdata'],
    methods: {
        sendEvent: function() {
            this.$emit('renew')
        }
    }
}
</script>

<style>

</style>

v-on을 사용해 하위 컴포넌트 AppHeader에서 생성한 this.$emit('이벤트명')을 바인딩 해줍니다. 그 다음론 실행할 메서드 이름을 명시해주면 준비가 끝납니다.


참고자료

'개발공부 > Vue.js 시작하기' 카테고리의 다른 글

[Vue.js] 싱글파일 컴포넌트  (0) 2021.09.26
[Vue.js] Vue CLI  (0) 2021.09.26
[Vue.js] 모르는 문법 나왔을 때 공부방법  (0) 2021.09.26
[Vue.js] watch와 computed  (0) 2021.09.26
[Vue.js] 템플릿 문법  (0) 2021.09.26