Vue.js 파일 

<template>
  <div>
      <div>
          <select v-model="selectedCity">
              <option :value="city.code" :key="i" v-for="(city,i) in cityList">{{city.name}}</option>
          </select>
          <input type="text" v-model="userName" @keyup.enter="searchUserList"/>
           //@keyup.enter 를통하여 엔터만 치더라도 조회가 가능하도록 함 
          <button type="button" @click="searchUserList">조회</button>
      </div>
      <div>
          <table>
              <thead>
                  <tr>
                      <th>이름</th>
                      <th>나이</th>
                      <th>직업</th>
                  </tr>
              </thead>
              <tbody>
                  <tr :key="i" v-for="(person,i) in userList">
                      <td>{{person.name}}</td>
                      <td>{{person.age}}</td>
                      <td>{{person.job}}</td>
                  </tr>
              </tbody>
          </table>
      </div>
  </div>
</template>
<script>
export default {
    name: '',
    components: {},
    data() {
        return {
            cityList : [
                {name : '서울', code:'02'},
                {name : '부산', code:'21'},
                {name : '제주', code:'06'}
            ],
            selectedCity:'',
            userName:'',
            userList:[]
    }
},
    methods: {
        searchUserList(){
          const params = {
              selectedCity : this.selectedCity,
              userName : this.userName
          }
          this.userList = this.getUserList(params);
        },
        getUserList(params){
            console.log(params);

            let list = [
                {name:'박보검', age:28, job:'연예인'},
                {name:'양세찬', age:33, job:'개그맨'},
                {name:'강동원', age:33, job:'연예인'},
                {name:'정우성', age:47, job:'연예인'},
            ];
            return list
        }

    }
}
</script>

List 조회화면

Save.vue

<template>
    <dir>
        <input type="text" v-model="userInfo.name">
        <input type="text" v-model.number="userInfo.age">
        <input type="text" v-model="userInfo.job">
        <button type="button" @click="saveUserInfo">저장</button>
    </dir>
</template>
<script>
export default {
    name: '',
    components: {},
    data() {
        return {
            userInfo: {
                name: '',
                age: '',
                job: '',
            }
    }
},
    beforeCreate() {},
    created() {},
    beforeMount() {},
    mounted() {},
    beforeUpdate() {},
    updated() {},
    beforeUnmount() {},
    unmounted() {},
    methods: {
        saveUserInfo(){
            if(this.userInfo.name == ''){
                return alert("사용자 이름을 입력하세요.");
            }
            if(this.userInfo.age == '' || this.userInfo.age == 0){
                return alert("나이를 입력하세요.");
            }
            // const params = {
            //     name : this.name,
            //     age : this.age,
            //     job : this.job
            // }
            const r = this.saveData(this.userInfo.params);
            if(r == 'S'){
                alert('사용자 정보가 생성되었습니다.')
            }
        },
        saveData(params){
            console.log(params);
            const r = 'S';
            return r;
        }
    }
}
</script>

 

# 랜더링 문법

1. v-if   vs v-show

v-if 는 조건에 따라 컴포넌트가 실제로 제거되고 생성된다.

v-show는 단순히 css 의 display 속성만을 변경 

 

# 이벤트 처리 

<div>
      <button type="button" v-on:click ="increaseCounter">Add 1 </button>
      <p>The Count is : {{counter}}</p>
  </div>
//methode 부분에 increaseCounter 함수를 만들어 줍니다.
increaseCounter() {
        this.counter = this.counter +1;
  }

 
[결과] Add1 버튼을 클릭시 Count가 증가합니다.
 
 

-- KeyUp 활용하는 방법 Vue.js 파일에 

<input type="text" v-model="textValue" @keyup.enter="showValue"/>

생성한 뒤 스크립트 부분의 메소드 부분에서 추가 

showValue(){
        alert(this.textValue);
      }

텍스트박스에 쓴 글씨를 쓰고 엔터를 눌렀을 경우 저렇게 Alert창이 뜨는 것을 볼수 있다.

#1  Vue 컴포넌트 기본구조 이해하기

 

1.1view 파일에 basic.vue파일 생성

<template>
<!-- hteml코드     -->
<h1>Hello World!!</h1>
</template>
<script>
export default {
    // 자바스크립트
}
</script>
<style scoped>
/* css */
</style>

1.2index.js 파일에 basic 부분 추가

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
//import Contact from '../views/Contact.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
3.
  ,{
    path: '/contact',
    name: 'Contact',
    component: () => import(/* webpackChunkName: "contact",webpackPrefetch:true */ '../views/Contact.vue')
  }
  // {
  //   path: '/contact',
  //   name: 'Contact',
  //   component: Contact
  // },
  ,{
    path: '/basic',
    name: 'Basic',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "basic" */ '../views/Basic.vue')
  }

]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

3. App.vue파일에 router-link 넣어주기 

<router-link to="/basic">Basic</router-link>

1.3이번엔 자바스크립트를 이용하여 데이터 보일수 있도록 하기

Baic.vue  ==> <h1>{{title}}</h1>   ,data부분 확인하기

<template>
<!-- hteml코드     -->
<h1>{{title}}</h1
</template>
<script>
export default {
    // 자바스크립트
    name: '',
    components: {},
    data(){
        return {
            title : 'Hello World1'
        }
    }
}
</script>
<style scoped>
/* css */
</style>

//input 타입으로 테스트 <!-- v-model : Value와 유사 -->

<template>
<!-- hteml코드     -->
<div>
<h1>{{title}}</h1>
<input type="text" v-model="title" />
</div>
<!-- v-model : Value와 유사 -->
</template>
<script>
export default {
    // 자바스크립트
    name: '',
    components: {},
    data(){
        return {
            title : 'Hello World1'
        }
    }
}
</script>
<style scoped>
/* css */
</style>

-- Vue 장점 : 양방향 데이터 통신

 

# 2.Vue.js 부분 간단한 Templeate 세트를 미리 작성해 놓고 사용하는 방법 (snippet)

 

2.1.F1을 눌러 snippet을 검색하고, preferences를 누름 

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

2.3.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"
        }
}

2.4.vue 파일에서 vue-start 치면 나옴

 

# 3.원시HTML 데이터 바인딩

3.1. Vue파일 생성 (DataBindingHtml.vue)

v-html 태그를이용하여 html이 적용될수 있도록 함

3.2 router/index.js 추가 주소추가

<template>
    <div v-html ="htmlString"></div>
</template>
<script>
export default {
    name: '',
    components: {},
    data() {
        return {
            htmlString: '<p style="color:red;">This is a red string.</p>'
    };
},
    beforeCreate() {},
    created() {},
    beforeMount() {},
    mounted() {},
    beforeUpdate() {},
    updated() {},
    beforeUnmount() {},
    unmounted() {},
    methods: {}
}
</script>

# 4. 입력폼 데이터 바인딩

4.1 input Text 부분을 활용

4.1.1dataBindingInputText.vue 생성 후 router/index.js에 주소추가

v-model을 이용한 데이터 바인딩

<template>
    <input type="text" v-model="example"/>
</template>
<script>
export default {
    name: '',
    components: {},
    data() {
        return {
            example: 'South Korea',
    };
},
    beforeCreate() {},
    created() {},
    beforeMount() {},
    mounted() {},
    beforeUpdate() {},
    updated() {},
    beforeUnmount() {},
    unmounted() {},
    methods: {}
}
</script>

4.2 number일경우, textarea 사용

v-model을 사용했을 경우 문자열로 인식  v-model.number 일경우 숫자로 인식

<template>
 <div>
    <input type="text" v-model="example" />
    <input type="number" v-model.number="example2" />
    <textarea v-model="example3"></textarea>
    <div>{{example3}}</div>
    <!-- v-model을 사용했을 경우 문자열로 인식
    v-model.number 일경우 숫자로 인식 -->
 </div>  
</template>
<script>
export default {
    name: '',
    components: {},
    data() {
        return {
            example: 'South Korea',
            example2: 12,
            example3: '안녕하세요.'
    };
},
    beforeCreate() {},
    created() {},
    beforeMount() {},
    mounted() {
        // console.log(example2); //이렇게 했을 경우 에러
        console.log(this.example2);
    },
    beforeUpdate() {},
    updated() {},
    beforeUnmount() {},
    unmounted() {},
    methods: {}
}
</script>

#5. 속성에 데이터 바인딩 하기

5.1 Example.vue 파일 생성

5.2 v-bind:disabled="textValue==''" 조건식을 주어 값이 없을 경우는 disabled 가 되도록 함

<template>
    <div>
        <!-- <img v-bind:src="url"  style="height:100px;width:auto;"/> -->
        <input type="text" v-model="textValue" />
        <button type="button" v-bind:disabled="textValue==''">click</button>
    </div>
</template>
<script>
export default {
    name: '',
    components: {},
    data() {
        return {
            url : 'https://kr.vuejs.org/images/logo.png',
            textValue:''
    }
},
    beforeCreate() {},
    created() {},
    beforeMount() {},
    mounted() {},
    beforeUpdate() {},
    updated() {},
    beforeUnmount() {},
    unmounted() {},
    methods: {}
}
</script>

#6. 클래스 데이터 바인딩 하기

<div class="container" v-bind:class="{'active':isActive, 'text-red': isBlue}">Class Binding </div>와 Data 부분 확인 

<template>
    <div class="container" v-bind:class="{'active':isActive, 'text-red': isBlue}">Class Binding </div>
</template>
<script>
export default {
    data() {
        return {
           isActive : true
           ,isBlue : true
        };
    }
}
</script>
<style scoped>
.container{
    width:100%;
    height: 200px;
}
.active {
    background-color: yellow;
    font-weight: bold;
}

.text-red{
    color: blue;
}
</style>

 

#7. 리스트 랜더링

# Vue Router 

클라이언트의 요청 경로에 따라 해당하는 컴포넌트를 불러와 페이지를 구성할 수 있다.

URL 변경시 DOM을 새로 갱신하는 것이 아니라 미리 컴포넌트를 가지고 있다가 변경된 요소 영역만을 갱신

따라서 유연하게 페이지 전환이 가능한다. vue-router라는 라우팅 라우브러리를 지원한다.

1. Vue Router 설치

vue add router 명령어 설치

History router 부분도 Y로 설치

Vue Src 에 Router 폴더가 생성됨을 확인 할수 있습니다.

View 파일을 클릭시에는 About.vue파일이 생성됨을 확인 할수 있습니다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

npm run serve 명령어로 서버를 실행시켜보겠음 about이 생김

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

router의 index.js 파일을 보면 rountes 안에 path,name,coponent 가 생김

import Home from '../views/Home.vue'  

component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')

about 은 component를 통해서 알려줌

path마다 컴포넌트를 연결해 줍니다.

main.js 파일로 가서 확인하면 router가 import되어있음을 확인 할수 있습니다.

createApp(App).use(router).mount('#app'
use(router)부분이 생성됨을 확인
구분을 편리하게 하기 위해 main.js 파일을 수정 함 
const app = createApp(App)
app.use(router)
app.mount('#app')  //.mount index.html의 div id 를 mount(load) 시켜라 <div id="app"></div>

App.vue 의 파일

-------------------------------------------------------------------------------

# Lazy Load(비동기컴포넌트)

index.js 파일에서

 

 

1번째 방식을 사용하게 되면 개발자도구 Network화면상에서 app.js 안에서 모든 componet들이 실행되도록 할수 있음(모든 클라이언트가 내려져 있어야함)

2번째 방식을 사용하게 되면

(캐시에만 담겨져 있다가,클릭하는 순간에 그때야 비로소 클라이언트에 내려줌,화면전환이 빠름)

# Vuel CLI 

CLI는 터미널에 명령어를 통해 컴퓨터와 상호작용

터미널을 이용하여 Vue 프로젝트를 생성하고, 관리하고,빌드하는 기능

Vue 프로젝트의 폴더 구조,필요한 파일들 기본설정 옵션을 명령어를  통해 자동으로 만들어줌

 

1.npm을 이용하여 Vue/cli 설치

sudo npm install -g @vue/cli

    -- -g (전역으로 설치 하겠다는 이야기) 따라서 윈도우 정보 admin 를 입력해줘야함 

       admin상태일 경우 sudo 없이 npm install -g @vue/cli

    

Vue 생성하는 방법 3가지

1. Default 옵션으로 생성하기                      

2. Manually select features 옵션으로 생성하기

3. Vue 프로젝트 매니저로 생성하기

 

1.Default 옵션으로 생성하기

  1.1 vue create vue-default 로 설치

     1.1.1 아래와 같은 오류일 경우  ==> vue.cmd create vue-default로 설치 

Default 일 경우 --> Router가 없음

Manually일 경우

--> Router 설치 O

--> Vue는 기본 Hash모드 

Hash모드는 url 뒤에 #이 붙는다.

History모드는 url 뒤에#이 붙지 않음

 

 

[Vue Router에서 HashMode VS History Mode차이점 참고] https://happy-coding-day.tistory.com/128 

 

 $ cd vue-default (내가 생성한 파일)로 이동 
 $ npm run serve (서버실행)

vue 파일 생성시 설치된 프로젝트 구조

--node_modules  : npm 으로 설치된 패키지 파일들이 모여 있는 디렉토리

--public : Webpack을 통해 관리되지 않는 정적 리소스가 모여 있는 디렉토리 

--src/assets : 이미지,css, 폰트 등을 관히하는 디렉토리

--src/components : Vue 컴포넌트 파일이 모여 있는 디렉토리

-- App.vue : 최상위(Root) 컴포넌트

--main.js : 가장 먼저 실행되는 자바스크립트 파일로써, Vue 인스턴스를 생성하는

                      역할을 담담

--gitignore : 깃허브에 업로할 때 제외할 파일 설정

--babel.config.js : 바벨 설절 파일

--package-lcok.json : 설치된 package의 디펜던시 정보를 관리하는 파일

--package.json : 프로젝트에 필요한 package를 정의하고 관리하는 파일

--ReadMe.md : 프로젝트 정보를 기록하는 파일

 

 

 

2. Manually select features 옵션으로 생성하기

 2.1 vue.cmd create vue-mannually로 설치 

스페이스바 누른후 선택

 

 

 

 

 

 

 

 

 

Choose Vue Version : Vue 버전을 선택

Bable : 

TypeScript : Vue에서 TyprScipt를 이용할때  

Progressive Web App(PWA) Support :  Web App기능을 지원

Router :Vue Router

Vuex : Vue 패키지 

CSS Pre-processors : css  전 처리패키지

Linter/ Formatter :

Unit Testing 

E2E Testing : 

-- Vue Option 선택지 였던 부분 차례대로 선택을 하게 됨

버전 3를 이용해서 해봄

 

 

 

 

 

 

 

 

Airbnb config : Airbnb에서 만든 표준 가이드

여기서는 Standard cofig 로 해서 사용함.

Lint on save 클릭함

각각의 config 파일로 할것인가를 설정하는 것인데 In Package.json으로 설정

동의한 프로세스대로 만들건가? yes 

preset 이름으로 Vue-baic으로 만들어서 앞으로 저 설정된 부분대로 파일을 편리하게 설정 할수 있음 

프로젝트 생성 후 PreSet이 잘 생성 되었는지 확인 해 볼려면 다른 파일을 생성을 하려면 옵션으로 내가 선택한 Preset이 생성된 것을 볼 수 있다.

3. Vue 프로젝트 매니저로 생성하기

3.1 vue.cmd ui 명령어 

localhost:8000번으로 들어가봄 

이런식으로 프로젝트를 클릭하여 만들 수 있음 (Vue-Basic과 동일하게 처리)

1.Viual Studio Code 설치 

2.node.js 설치

3. 터미널을 킨 후 node-v 를 통해  버전 확인

4. npm -v  으로 npm 버전 확인

 

-- Node.js 

서버프로그램 개발을 자바스크립트로 가능하도록 하는 자바스크립트 런타임 환경

일반적으로 자바스크립트는 웹브라우저에서 클라이언트에 돌아가는 방식이지만,

Node.js는 자바스크립트를 이용하여 서버프로그램을 실행할 수 있는 것 

 

--NPM (Node Package Manager)

수 많은 오픈소스 자바스크립트 패키지가 등록되어있고, 이를 사용할 수 있도로고 해주는 플랫폼 

 

--확장 프로그램을 이용 하여 Vetur설치 ( 자세한 설명 및 오류부분을 잘 찾아줌)

-- Prettier - Code formatter 설치 (코드 예쁘게 나오기)

-- Vue 3 Snippers 설치 

 

 

+ Recent posts