Vue3 정복기(10일차 - 1)

최충열·2022년 5월 23일
post-thumbnail

Slot 보장

App.vue

slot의 역할! v-slot은 #으로 표현되며, MyBtn에 name으로 icon, text 순서를 정할 시, App.vue에 text가 앞으로 나와도 icon이 먼저 나오는 순서가 보장된다.


<template>
  <!-- v-slot= # , v-on= @, v-bind = : -->
  <MyBtn>
    <template #text>
      <span>Banana</span>
    </template>
    <template #icon>
      <span>(B)</span>
    </template>
  </MyBtn>
</template>

<script>
import MyBtn from "~/components/MyBtn";

export default {
  components: {
    MyBtn,
  }
};
</script>
MyBtn
<template>
  <div class="btn">
    <slot name="icon"></slot>
    <slot name="text"></slot>
  </div>
</template>

<script>
export default {
 
}
</script>

<style scoped>
  .btn {
    display: inline-block;
    margin: 4px;
    padding: 6px 12px;
    border-radius: 4px;
    background-color: gray;
    color: white;
    cursor: pointer;
  }
</style>
provide, inject

하위컴포넌트로 내려갈때는 props로 지정하지만, 한번에 자손요소 컴포넌트로 이동할때는 provide와 inject를 사용하게된다. 하지만 반응성을 가지지못해서 computed를 활용해서 return을 돌려주게끔 만들어야한다.

컴포넌트 - Refs

refs의 사용방법

$refs를 이용해서 객체를 선택할수있으며, 자식컴포넌트인 Hello.vue를 통해서 도출하고있다.

<template>
  <Hello ref="hello" />
</template>

<script>
import Hello from '~/components/Hello'

export default {
  components: {
    Hello
  },
  // ref는 mounted에서만 사용가능
  mounted() {
    console.log(this.$refs.hello.$refs.good)
  }
};
</script>
<template>
  <h1>Hello~</h1>
  <h1 ref="good">
    Good?
  </h1>
</template>

컴포지션 API 맛보기

ref를 이용해서 반응성만들기

setup 매소드를 이용해 Api 제작을 한다. 기본 데이터는 주석쳐진 내용을 setup 매소드안에 새롭게 넣어 제작하며
본래 count = 0으로 넣으면 반응성을 가질수없기때문에 ref를 vue 패키지로 들고온다.
count = ref(0)으로 넣고 객체데이터를 count.value를 활용하여 클릭 시, +=1씩 증가하도록 반응성을 가지게 된다.

<template>
  <div @click="increase">
    {{ count }}
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  // data() {
  //   return {
  //     count: 0
  //   }
  // },
  // methods: {
  //   increase() {
  //     this.count += 1
  //   }
  // },
  setup() {
    // ref(0)은 객체 데이터, count.value해야 가능
    let count = ref(0)
    function increase() {
      count.value += 1
    }

    return {
      count,
      increase
    }
  }
}
</script>
profile
프론트엔드가 되고싶은 나

0개의 댓글