[Vue.js] 싱글 파일 컴포넌트

Yujin Lee·2021년 5월 12일
0

Vue.js

목록 보기
12/18
post-thumbnail

1.

단축키

scf

안되면

vue


App.vue

<template>
    <div>
    
    <!-- div는 무조건 하나 -->
    
    </div>
</template>

<script>

</script>


<style>

</style>



2. 싱글 파일 컴포넌트 체계에서 컴포넌트 등록하기

App.vue

<template>
  <div>
    <app-header></app-header>
  </div>
</template>

<script>
import AppHeader from './components/AppHeader.vue'; 
// 컴포넌트에 내용을 정리하고 그 내용을 받아서 변수로 넣음

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




3. 싱글 파일 컴포넌트에서 props 속성 사용하기

App.vue

<template>
  <div>
    <!-- <app-header v-bind:프롭스 속성 이름="상위 컴포넌트의 데이터 이름"></app-header> -->
    <app-header 
      v-bind:propsdata="str"
  </div>
</template>

./components/AppHeader.vue (<- 이처럼 두 단어로 조합하고, 단어의 첫글자를 대문자로 쓰는 문법 사용)

<template>
  <header>
    <h1>{{ propsdata }}</h1>
  </header>
</template>

<script>
export default {
  props: ['propsdata']
  //propsdata에 데이터를 내려 보내줄 수 있게 됨
}
</script>




4. 싱글 파일 컴포넌트에서 event emit 구현하기

버튼 생성

./components/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'); 
      // 여기에 정의한 이벤트가 App.vue 로 전달됨
    }
  }
}
</script>

App.vue

<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: 'Header'
    }
  },
  components: {
    'app-header': AppHeader
  },
  methods: {
    renewStr: function() {
      this.str = 'hi';
    }
  }
}
</script>

<style>

</style>
profile
I can be your Genie🧞‍♀️ How ‘bout Aladdin? 🧞‍♂️

0개의 댓글