Vue.js 에서 v-for 객체배열을 통해 반복문을 연습하기 예제입니다.

 

<template>
    <main>
        <h1>반복문 사용하기</h1>
        <table>
            <thead>
                <tr>
                    <th>제품명</th>
                    <th>가격</th>
                    <th>카테고리</th>
                    <th>배송료</th>
                </tr>
            </thead>
            <tbody>
                <tr :key="i" v-for="(product, i) in products">
                    <td>{{ product.name }}</td>
                    <td>{{ product.price }}</td>
                    <td>{{ product.category }}</td>
                    <td>{{ product.delivery }}</td>
                </tr>
            </tbody>
        </table>
    </main>
</template>
<script>
export default {
    name: '',
    components: {},
    data() {
        return {
            products: [
                { name: '게이밍마우스', price: 34500, category: '컴퓨터/주변기기', delivery: 4000 },
                { name: '무선게이밍마우스', price: 52000, category: '컴퓨터/주변기기', delivery: 3000 },
                { name: '게이밍키보드', price: 42000, category: '컴퓨터/주변기기', delivery: 3000 },
                { name: '무선게이밍키보드', price: 50000, category: '컴퓨터/주변기기', delivery: 4000 },
                { name: '무선충전기기', price: 24000, category: '컴퓨터/주변기기', delivery: 3000 },
                { name: '갤럭시탭', price: 385000, category: '모바일/휴대기기', delivery: 0 },
            ]
        }
    },
    methods: {}
}
</script>

 

오히려 이전 발행글보다 난이도가 낮아진 기초의 느낌입니다.

 

 

[ Vue.js ] 반복문 사용하기 for .. in .. , 객체 리스트 출력하는 방법

안녕하세요 상훈입니다. Vue.js에서 반복문을 사용하고, 그 속에서 data binding이 된 객체 데이터를 출력하는 방법을 포스팅하겠습니다. 1. data 2. template 1. data import products from './assets/listData.j..

code-hoon.tistory.com

 

 

반응형

 

Canvas.js 를 사용하는 와중 특정한 조건에 의해 새로운 차트비동기로 재출력하는 상황,
아래와 같은 에러가 발생하였다.

 

 

이유인즉슨, 기존의 차트가 존재하기 때문에 새로운 차트를 적용할 수 없다는 것이다.

 

그렇기 때문에 기존의 차트를 제거하는 수순을 밟아야한다.

 const ChartName = new Chart(
        document.getElementById('generalList'),			// canvas의 id 호출
        ChartNameConfig								// Config로 기본 설정했던 변수 호출
      );
      ChartName.destroy()							// ★★destroy로 기존의 canvas를 제거
  }

destroy()new Chart 함수의 마지막에 작성한다.

 

 

 

https://pretagteam.com/question/canvas-is-already-in-use-chart-with-id-0-must-be-destroyed-before-the-canvas-can-be-reused-chatjs

 

pretagteam.com

 

해당 페이지 참고

반응형

 

Vue.jstemplate 세트를 원하는 부분에 미리 작성해놓고 사용하는 방법이 있습니다.

물론 기본적으로 ctrl  + space 만 눌러도 template, script, style 이 세가지가 다 나오지만, 

잠깐 귀찮으면서 미리 작성해놓으면 원하는 내용을 추가적으로 등록해놓을 수 있습니다.

결과물

이런식으로 말이죠.

 

F1을 눌러 snippet을 검색하고, preferences를 누릅니다.

 

그 다음 vue 를 검색하여 vue.json을 클릭합니다.

 

vue.json 파일이 열리며, 이곳에 작성해주시면 됩니다.

 

{ 
// ...
"Generate Basic Vue Code" : {
		"prefix": "vue-start",
		"body": [
			"<template>\n\t<main>\n\n\t</main>\n</template>\n<script>\nexport default {\n\tname: '',\n\tcomponents: {},\n\tdata() {\n\t\treturn {\n\t\t\texample: '',\n\t}\n},\n\tbeforeCreate() {},\n\tcreated() {},\n\tbeforeMount() {},\n\tmounted() {},\n\tbeforeUpdate() {},\n\tupdated() {},\n\tbeforeUnmount() {},\n\tunmounted() {},\n\tmethods: {}\n}\n</script>"
		],
		"description": "Generate Basic Vue Code"
	}
}

prefix 부분에 명령어와 같이 vue-start를 입력하면 해당 body 포멧을 불러올 수 있게 됩니다.

body 부분에 원하는 내용을 작성하는 것입니다.

 

추가.

created & mounted 메서드만

{
"Generate Other Vue Code" : {
		"prefix": "vue-other",
		"body": [
			"<template>\n\t<main>\n\n\t</main>\n</template>\n<script>\nexport default {\n\tname: '',\n\tcomponents: {},\n\tdata() {\n\t\treturn {\n\t\t\texample: '',\n\t}\n},\n\tcreated() {},\n\tmounted() {},\n\tmethods: {}\n}\n</script>"
		],
		"description": "Generate Basic Vue Code"
	}
}

 

 

이상입니다.

 

반응형

 

Vue.js Cli 3 부터 prefetch 기능이 추가 되었습니다!

 

■ prefetch란?

pre + fetch 로, fetch를 선행한다는 뜻입니다. 
기본적으로 Vue.js에서는 prefetch = true로 설정되어져 있고, 이를 vue.config.js 에서 수정이 가능합니다.
브라우저가 미리 캐시(cache) 하는 것으로, 브라우저를 사용하는데에 빠르다고 느낄 수 있다.

vue.config.js 에서 prefetch 제거하기

 

■ 사용 목적

1. 렌더링 시간 단축
    => 하지만, 잘못 사용 시 오히려 렌더링 시간이 증가하게 된다. 

 

■ 특징

- Lazy Load가 적용된  Components는 모두 prefetch 기능이 적용 된다. (= 캐시가 미리 저장된다)
- 비동기 컴포넌트로 정의된 모든 리소스들을 캐시에 담기 때문에 요청(request) 수 증가한다.
- 초기 화면은 오히려 느림
    => 마지막에 다운로드 받기 때문이다.
        => 따라서 초기 렌더링은 prefetch사용하지 않는 것이 더 빠르다.

 

■ 추가

- Vue Application 개발 시 기본적으로 prefetch는 끄는 것을 권장한다.
- vue-router에서 주석으로 처리된 "webpackPrefetch: true" 를 넣어주면 prefetch가 적용된다.

main.js

 

 

 

 

반응형

 

Javascript로 select box 내의 option들을 특정 조건에 의해 함수를 호출하여 제거하려고 한다. 
검색 기능으로 사용하면 유용하다.

 

물론 select box 말고도 p, span, div...등등 부모-자식 관계의 태그들이라면 모두 가능하다.

 

Node . removeChild 를 사용한다.

const item_name = document.querySelector('#item_name')	// item_name이라는 부모 요소
while (item_name.firstChild) {		// 첫번째 자식 태그가 존재하면 무한 반복
      item_name.removeChild(item_name.firstChild);		// 첫번째 자식 태그를 제거한다. 
 }

 

item_name 이라는 id를 가진 태그를 querySelector로 가져온다.

가져온 태그 내 자식 태그가 1개 이상일 때 반복문이 실행된다.

그리고 removeChild를 통해 자식요소를 제거한다.

 

 

 

Node.removeChild() - Web APIs | MDN

The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node.

developer.mozilla.org

 

반응형

 

npm으로 생성한 프로젝트를 원하는 임의의 포트로 실행하는 방법

// 3100포트 번호로 해당 프로젝트 실행 
$ npm run serve -- --port 3100

 

■ 결과

localhost:3100  으로 해당 프로젝트가 실행됨

 

반응형

 

Vue.js 에서 Bootstrap을 사용하고 싶을 때 cdn을 이용하는 방법 이외에 npm, yarn 등을 이용해서 직접설치를 한다.

그래서 나온 것이 BootstrapVue 이다.

 

# With npm
$ npm install vue bootstrap bootstrap-vue

# With yarn
$ yarn add vue bootstrap bootstrap-vue

 

 

BootstrapVue

Quickly integrate Bootstrap v4 components with Vue.js

bootstrap-vue.org

이곳이 링크이다. 참고 바람

 

◆ Vue.js 3 에서는 아직 적용이 안되니 주의 바랍니다 ◆

 

 

 

 

반응형

 

Vue.js 에서 class에 변화를 주고 싶을 때 사용한다.
class태그의 변화는 data 객체에 있는 데이터의 변화로 인해 바뀌게 설정하는 것이 일반적이다.

 

<span 
  @click="changeStatus(index)" 
  class="pointer"
  :class="{'text-danger fw-bold': task.status ==='to-do',
  'text-warning': task.status === 'in-progress',
  'text-success': task.status === 'finished'
  }"
  >
  {{ firstCharUpper(task.status) }}
</span>

<script>
data () {
    return { 
      availableStatuses: ['to-do', 'in-peogress', 'finished'],
      tasks: [
        {
          name: 'Steal bananas from the stroe',
          status: 'to-do'
        }
    }
  },
  methods: {
  	changeStatus(index){	//메서드명
      let newIndex = this.availableStatuses.indexOf(this.tasks[index].status)	// status의 index 파악 후 newIndex 할당
      if(++newIndex > 2) newIndex = 0		// 만약 newIndex가 2초과시, newIndex = 0
      this.tasks[index].status = this.availableStatuses[newIndex]		// avaiableStatuses[] 배열의 내용 순차 입력
    },
  }
</script>

 

이렇게 span 태그를 클릭할 때마다 availableStatuses [] 내 내용이 순차적으로 span태그에 출력이 된다. 

이럴 때, 해당 문구(availableStatuses[ ]) 에 따라서 class를 바꾸고 싶을 때 사용한다.

해당 내용은 글로 보기에는 난해한 부분이 있으므로,
직접 손으로 작성해나가면서 이해하는것이 좋다.

 

결과 이미지

 

 

해당 강의 내용 중 발췌

 

이상

- 조금 더 쉬운 예제를 가지고 오는건 어떨까 싶기도하다.

 

 

반응형

+ Recent posts