티스토리 뷰

Javascript/Vue

03. Vue - 기초 정리

akatjd 2022. 9. 25. 18:35

1. Naming Rule (Views)

 - 이름 맞추고 끝에 ****View.vue로 맞춰줌. (3 버전 들어와서 네이밍 룰 생김)

 

2. vue파일 내부 style 테그

 - scoped가 붙으면 해당 파일내에만 적용. 빠지면 전체 컴포넌트에 적용.

 

3. webpackChunkName

 - 여러 라우팅에 동일 chunk name으로 묶어주면 하나의 js 파일로 묶어줌.

 

4. v-html=""

 - 해당 테그를 통해 script return에서 만들어준 html 데이터를 삽입해준다.

   (ex : <div v-html="hiHtml"></div> div 가운데 inner html로 삽입해줌)

 

5. v 관련 테그는 양방향 바인딩이다.

 - js 쪽에서 바꿔도 웹에서 바꿔도 해당 데이터는 변경됨.

 - 앵귤러, 리액트에서는 양방향 바인딩 제공을 안해줌.

 

6. onclick 이벤트

 - vue에서는 @click 사용

  (ex : <button @click="myFunction"></button>)

   콘솔 창 확인하면 버튼 누를 때마다 userId 값이 찍힘. 데이터를 바꾸면 해당 데이터로 바뀌어 찍힘.

 

7. checkbox의 v-model은 체크박스와 바인딩 되어 있음.

<template>
  <div>
    <div>
      <input type="checkbox" name="" id="html" value="HTML" v-model="favoriteLang" />
      <label for="html">HTML</label>
    </div>
    <div>
      <input type="checkbox" name="" id="css" value="CSS" v-model="favoriteLang" />
      <label for="css">CSS</label>
    </div>
    <div>
      <input type="checkbox" name="" id="js" value="JS" v-model="favoriteLang" />
      <label for="js">Javascript</label>
    </div>
    <div>선택한 지역: {{ favoriteLang }}</div>
  </div>
</template>

<script>
export default {
  name: 'DataBindingCheckboxView',
  data() {
    return {
      favoriteLang: []
    }
  }
}
</script>

<style scoped>

</style>

8. radio는 데이터 선언이 문자열로 됨. (checkbox는 배열)

<template>
  <div>
    <div>
      <input type="radio" name="" id="html" value="HTML" v-model="favoriteLang" />
      <label for="html">HTML</label>
    </div>
    <div>
      <input type="radio" name="" id="css" value="CSS" v-model="favoriteLang" />
      <label for="css">CSS</label>
    </div>
    <div>
      <input type="radio" name="" id="js" value="JS" v-model="favoriteLang" />
      <label for="js">Javascript</label>
    </div>
    <div>선택한 지역: {{ favoriteLang }}</div>
  </div>
</template>

<script>
export default {
  name: 'DataBindingRadioView',
  data() {
    return {
      favoriteLang: ''
    }
  }
}
</script>

<style scoped>

</style>

9. attribute

 - readonly 등의 경우 양방향 바인딩이 필요없어 v-bind를 통해 단방향 바인딩 함.

 - v-bind:value 이런식에서 v-bind 생략 후 ':' 표현만으로 가능함.

 - :disabled="txt1 === ''" 등의 조건을 넣어서 옵션을 활성화/비활성화 할 수 있음.

<template>
  <div>
    <input type="text" name="" id="" v-bind:value="userId" readonly />
    <input type="text" name="" id="" :value="userId" readonly />
    <br>
    <img :src="imgSrc" alt="" style="width: 100px; height: auto;">
    <br>
    <input type="search" name="" id="" v-model="txt1" />
    <button :disabled="txt1 === ''">조회</button>
  </div>
</template>

<script>
export default {
  name: 'DataBindingAttributeView',
  data() {
    return {
      userId: 'kms',
      imgSrc: 'https://upload.wikimedia.org/wikipedia/commons/f/f1/Vue.png',
      txt1: ''
    }
  }
}
</script>

<style scoped>

</style>

10. list

 - v-for를 통해 리스트를 뿌려줄 수 있음.

 - v-for 사용시에는 바인딩 한 key값이 필요하며, 고유값이어야 함.

 - 쓰는 방법은 아래와 같음.

 - key로 쓸값이 없으면 index 사용 가능. (ex : (drink, i) in drinkList 이렇게 지정하고 키값에 i 넣으면 됨)

<template>
  <div>
    <div>
      <select name="" id="">
        <option value=""></option>
        <option :value="city.code" :key="city.code" v-for="city in cities">{{ city.title }}</option>
      </select>
    </div>
    <div>
      <table>
        <thead>
          <tr>
            <th>제품번호</th>
            <th>제품이름</th>
            <th>가격</th>
            <th>주문수량</th>
            <th>합계</th>
          </tr>
        </thead>
        <tbody>
          <tr :key="drink.drinkId" v-for="drink in drinkList">
            <td>{{ drink.drinkId }}</td>
            <td>{{ drink.drinkName }}</td>
            <td>{{ drink.price }}</td>
            <td><input type="number" name="" id="" v-model="drink.qty"></td>
            <td>{{ drink.price * drink.qty }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DataBindingListView',
  data() {
    return {
      cities: [
        { title: '서울', code: '02' },
        { title: '부산', code: '051' },
        { title: '제주', code: '064' }
      ],
      drinkList: [
        {
          drinkId: '1',
          drinkName: '콜라',
          price: 12220,
          qty: 123
        },
        {
          drinkId: '2',
          drinkName: '오렌지주스',
          price: 1110,
          qty: 20
        },
        {
          drinkId: '3',
          drinkName: '사이다',
          price: 700,
          qty: 300
        }
      ]
    }
  }
}
</script>

<style scoped>

</style>

11. class

 - class를 바인딩 할 수 있고 true값을 지정해줘야 들어감.

 - 여러개 클래스 지정 가능.

 - 안에 '-'가 들어가지 않은 클래스는 싱글 쿼터로 안묶어줘도 됨. (있으면 넣어줘야 함)

 - 배열로도 class 설정 가능하지만 실무에서 그렇게 쓰는 경우는 드뭄.

<template>
  <div>
    <div :class="{ 'text-red': hasError, active: isActive }">클래스 바인딩</div>
    <div :class="class2">클래스 바인딩2</div>
  </div>
</template>

<script>
export default {
  name: 'DataBindingClassView',
  data() {
    return {
      isActive: false,
      hasError: false,
      class2: ['active', 'hasError']
    }
  }
}
</script>

<style scoped>
  .active {
    background-color: greenyellow;
    font-weight: bold;
  }
  .text-red {
    color: red;
  }
</style>

12. style

<template>
  <div>
    <div style="color: red; font-size: 30px;">
      스타일 바인딩: 글씨는 red, 폰트크기:30px
    </div>
    <div :style="style1">
      스타일 바인딩: 글씨는 green, 폰트크기:30px
    </div>
    <button @click="style1.color='blue'">색상바꾸기</button>
  </div>
</template>

<script>
export default {
  name: 'DataBindingStyleView',
  data() {
    return {
      style1: {
        color: 'green',
        fontSize: '30px'
      }
    }
  }
}
</script>

<style scoped>

</style>

13. change event

 - change에서 event를 넘겨줄거면 ($event)를 붙여준다.

   밑에 예시에서 event 찍어보면 select가 찍힘.

<template>
  <div>
    <select name="" id="" @change="changeCity($event)" v-model="selectedCity">
      <option value="">==도시선택==</option>
      <option :value="city.cityCode" :key="city.cityCode" v-for="city in cityList">
        {{ city.title }}
      </option>
    </select>
    <select name="" id="">
      <option :value="dong.dongCode" :key="dong.dongCode" v-for="dong in selectedDongList">
        {{ dong.dongTitle }}
      </option>
    </select>
  </div>
</template>

<script>
export default {
  name: 'EventChangeView',
  data() {
    return {
      selectedCity: '',
      cityList: [
        { cityCode: '02', title: '서울' },
        { cityCode: '051', title: '부산' },
        { cityCode: '064', title: '제주' }
      ],
      dongList: [
        { cityCode: '02', dongCode: '1', dongTitle: '서울 1동' },
        { cityCode: '02', dongCode: '2', dongTitle: '서울 2동' },
        { cityCode: '02', dongCode: '3', dongTitle: '서울 3동' },
        { cityCode: '02', dongCode: '4', dongTitle: '서울 4동' },
        { cityCode: '051', dongCode: '1', dongTitle: '부산 1동' },
        { cityCode: '051', dongCode: '2', dongTitle: '부산 2동' },
        { cityCode: '051', dongCode: '3', dongTitle: '부산 3동' },
        { cityCode: '064', dongCode: '1', dongTitle: '제주 1동' },
        { cityCode: '064', dongCode: '2', dongTitle: '제주 2동' }
      ],
      selectedDongList: [

      ]
    }
  },
  methods: {
    changeCity(event) {
      console.log(event.target.tagName) // select 찍힘
      this.selectedDongList = this.dongList.filter(
        dong => dong.cityCode === this.selectedCity
      )
    }
  }
}
</script>

<style scoped>

</style>

14. click event

<template>
  <div>
    <button @click="increaseCounter">Add 1</button>
    <p>{{ counter }}</p>
  </div>
</template>

<script>
export default {
  name: 'EventClickView',
  data() {
    return {
      counter: 0
    }
  },
  methods: {
    increaseCounter() {
      this.counter += 1
    }
  }
}
</script>

<style scoped>

</style>

15. key event

 - keyup을 통해 키보드 상태를 다양하게 체킹할 수 있음.

<template>
  <div>
<!--    <input type="search" name="" id="" @keyup="checkEnter($event)" v-model="searchText">-->
    <input type="search" name="" id="" @keyup.enter="checkEnter($event)" v-model="searchText">
    <button @click="doSearch">조회</button>
  </div>
</template>
// .enter
// .tab
// .delete
// .esc
// .space
// .up
// .down
// .left
// .right
// .stop - event.stopPropagation()
<script>
export default {
  name: 'EventKeyView',
  data() {
    return {
      searchText: ''
    }
  },
  methods: {
    doSearch() {
      console.log(this.searchText)
    },
    checkEnter(event) {
      if (event.keyCode === 13) {
        this.doSearch()
      }
    }
  }
}
</script>

<style scoped>

</style>

'Javascript > Vue' 카테고리의 다른 글

05. Vue - Login 구현 (+ Spring security)  (0) 2022.09.28
04. Vue - Axios  (0) 2022.09.26
02. Vue - router  (0) 2022.09.25
01. Vue 3 - create package 설정  (1) 2022.09.25
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함