TODAY TOTAL
Front-End/Vue (2)
[Vue] 기초-2

 

v-for-exer.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="http://cdn.jsdelivr.net/npm/vue"></script>
    <style>
        /* 화면에 렌더링 할 때 사용할 제목의 색상을 파란색으로 정의 */
        .blue_style {color: blue}
    </style>
</head>
<body>
    <div id="app">
        <h1>윤고랭이가 좋아하는 과일은?</h1>
        <ul>
            <!-- v-for를 통해서 반복문으로 aFruits 과일 배열 데이터를 가져옴 -->
            <li v-for="(items, index) in aPersons">
                <!-- aFruits 안의 항목을 하나씩 꺼내서 HTML로 렌더링 -->
                <p>번호 : {{ index }}</p>
                <p>이름 : {{ items.name }}</p>
                <p>나이 : {{ items.age }}</p>

            </li>
        </ul>
    </div>
    <script>
        Vue.config.devtools=true;
        //F12 개발자모드 출력
    var app = new Vue({
        el : '#app',
        data : {
            aPersons: [
                {
                    name : '홍길동',
                    age : 27
                },
                {
                    name : '이순신',
                    age : 30
                },
                {
                    name : '강감찬',
                    age : 35
                }
            ]
        }
    });
    </script>

</body>
</html>

for...in:

반복문은 객체의 모든 열거 가능한 속성애 대해 반복

기본적인 for문과는 다르지만, 프로퍼티를 순회 할 수 있도록 합니다.

 

루프마다 객체의 열거할 수 있는 프로퍼티의 이름을 지정된 변수에 대입

 

 

for(변수 in 객체) {

       객체의 모든 열거할 수 있는 프로퍼티의 개수만큼 반복적으로 실행하고자 하는 실행문;

}

 

<li v-for="(items, index) in aPersons">

items,index는 변수이고 aPersons라는 객체

 

 

::결과화면

 

프로퍼티 개수만큼 실행됨.


 

computed.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="http://cdn.jsdelivr.net/npm/vue"></script>
    <style>
        /* 화면에 렌더링 할 때 사용할 제목의 색상을 파란색으로 정의 */
        .blue_style {color: blue}
    </style>
</head>
<body>
    <div id="app">
        <p>원본 문장 : "{{ sOriginalMessage }}"</p>
        <p>대문자 변환 문장 : "{{ fnUpperCaseMsg }}"</p>
    </div>
    <script>
        Vue.config.devtools=true;
    new Vue({
        el : '#app',
        //data는 메스태시 안에 넣을 값이 간단할 때 사용
        data : {
            sOriginalMessage : 'How are you?'
        },
        // computed는 머스태시 안에 넣을 JS 로직이 복잡할 때 사용
        computed: {
            fnUpperCaseMsg: function() {
                return this.sOriginalMessage.toUpperCase();
            }
        }

        // computed 속성
        // 머스태시에 작성할 로직이 복잡하면 함수로 정의할 때
        // 계산량이 많아서 캐시가 필요할 때

        // methods 속성
        // 뷰의 이벤트 핸들러 로직을 함수로 정의할 때
    });
    </script>

</body>
</html>

 

computed :

템플릿 내에 표현식을 넣으면 편하다. 하지만 간단한 연산 일때만 이용하는 것이 좋은데,

왜냐하면 너무 많은 연산을 템플릿 안에서 하면 코드가 비대해지고 유지보수가 어렵다.

 

복잡한 로직이면 사용하는게 computed 속성

 

 

component_basic.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="http://cdn.jsdelivr.net/npm/vue"></script>
    <style>
        .fruit_style {
            border : 1px solid #ccc;
            background-color: white;
            padding-left : 1em;
        }
    </style>
</head>
<body>
    <div id="app">
        <h1>{{ sTitle }}</h1>
        <favorite-fruits></favorite-fruits>
        <favorite-fruits></favorite-fruits>
    </div>
    <script>
        Vue.config.devtools=true;
        Vue.component('favorite-fruits',{
            data: function() {
                return {
                    aFruits : 
                [
                    { sFruitName : '사과'}
                    ,{ sFruitName : '오렌지'}
                    ,{ sFruitName : '수박'} 
                ]
                }
            },
            template:`
            <div>
                <div v-for="item in aFruits" class = "fruit_style">
                    <p>좋아하는 과일 : {{ item.sFruitName }}</p>
            </div>
                <br>
            </div> `
        })
    new Vue({
        el : '#app',

        data : {
            sTitle : 'How are you?'
        }
    });
    </script>

</body>
</html>

template :

HTML, CSS 등의 마크업 속성과 뷰 인스턴스에서 정의한 데이터 및 로직들을 연결하여

사용자가 브라우저에서 볼 수 있는 형태의 HTML로 변환해 주는 속성입니다.

 

 

<div>
                <div v-for="item in aFruits" class = "fruit_style">
                    <p>좋아하는 과일 : {{ item.sFruitName }}</p>
                </div>
                <br>

</div> `

 

이 형태를 HTML로 변환해줘서 보여준다.

머스태시를 쓸 수 있다.

 

 

 

 

methods.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="http://cdn.jsdelivr.net/npm/vue"></script>
    <style>
        /* 화면에 렌더링 할 때 사용할 제목의 색상을 파란색으로 정의 */
        .blue_style {color: blue}
    </style>
</head>
<body>
    <div id="app">
        <p>클릭 숫자   : {{ nClicks }}</p>
        <p>카운트 다운 : {{ fnCounter }}</p>
        <button v-on:click="fnIncrement"> 눌러줘 </button>
    </div>
    <script>
        Vue.config.devtools=true;
    new Vue({
        el : '#app',

        data : {
            nClicks: 0
        },
        computed: {
            fnCounter: function() {
               return 10 - this.nClicks
               //클릭 할 때마다 차감이 된다.
            }
        },
        methods : {
            fnIncrement() {
                this.nClicks++;
                //methods 렌더링이 일어날때마다 항상 실행
            }
        }

    });
    </script>

</body>
</html>

 

methods:

종속된 값이란 개념없이 렌더링이 일어날 때마다 계속 호출이 된다.

 

그러면 computed와 다른 점은 뭘까

 

computed는 계산해야하는 목표 데이터를 정의하는 '선언형' 프로그래밍 방식

종속 대상의 변경이 일어나기 전까지는 호출이 되지 않고

 

methods는 렌더링이 일어날 때마다 항상 함수를 실행합니다.

 

computed는 반환하는 결과를 캐싱 해줍니다.

 

하지만 헤비, 무거운 로직이라면 렌더링이 일어날 때마다 항상 실행하는 methods보단

computed 속성으로 구현하는게 더 좋다.

 

 

'Front-End > Vue' 카테고리의 다른 글

[Vue] 기초  (0) 2021.07.22
  Comments,     Trackbacks
[Vue] 기초

 

 

브라우저는 크롬으로 사용.

Vue를 크롬 확장프로그램을 추가해야하는데

구글에 'Vue 크롬 확장 프로그램' 이라 치면 바로 첫번째로 구글 확장프로그램이 나온다 클릭

 

 

 

설치를 하면 

Vue 확장 아이콘 오른쪽버튼 누르고 '확장 프로그램 관리' 클릭

 

허용 스위치 하기

 

먼저 Vue사이트에서 기본적인 문법, 용어 알아보기

 

https://kr.vuejs.org/v2/guide/instance.html

 

Vue 인스턴스 — Vue.js

Vue.js - 프로그레시브 자바스크립트 프레임워크

kr.vuejs.org

 

hello_vuejs.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="http://cdn.jsdelivr.net/npm/vue"></script>
    //Vue script
</head>
<body>
    <div id="main">
        <p>{{ sTitle }}</p>
        <p>{{ sName }}</p>
        <p>{Hi}</p>
    </div>
    <script>
     Vue.config.devtools=true; //이걸 써줘야 F12 눌렀을때 Vue 탭이 나온다.
     
        //1. 뷰 CDN 설정
        //2. 뷰 인턴스 생성
        //3. 화면에 데이터 바인딩
        //   데이터 출력은 머스태시({{ }}) 템플릿 사용
        new Vue({
            el: "#main",
            data: {
                sTitle: "안녕하세요!",
                sName: "누구세요?",
                Hi : "Hi"
            }
        });

    </script>

</body>
</html>

 

 

데이터출력은 {{}} 머스태시 템플릿

 

이게 머스태시. 비슷하긴 하넹

 

 

 

Vue는 초보자도 쉽게 할 수 있는거 같고, 눈에 보기에도 명확해서 보기 좋은거 같다.

 

 

v-bind.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="http://cdn.jsdelivr.net/npm/vue"></script>
    <style>
        /* 화면에 렌더링 할 때 사용할 제목의 색상을 파란색으로 정의 */
        .blue_style {color: blue}
    </style>
</head>
<body>
    <div id="main">
        <!-- v-bind 안에서도 스크립트를 사용할 수 있으므로 변수와 문장을 연결 -->
        <!-- v-bind 디렉티브 -->
        <h1 v-bind:class="sColorName + '_style'">안녕하세요</h1>
        <p>{{sTitle}}</p> <!-- HTML 엘리먼트값을 만듦 -->
        <input v-bind:value="sDate"><!-- HTML 어트리뷰트 값을 만듦 -->
    </div>
    <script>
        Vue.config.devtools=true;
        //1. 뷰 CDN 설정
        //2. 뷰 인턴스 생성
        //3. 화면에 데이터 바인딩
        //   데이터 출력은 머스태시({{ }}) 템플릿 사용
        new Vue({
            el: '#main',
            data:{
                //Date 객체의 getFullYear() 메서드로 올해 문장 준비
                sTitle: '반가워',
                sDate: '올해 연도:' + new Date().getFullYear(),
                sColorName:'blue'
            }
        });

    </script>

</body>
</html>

 

하면서 뭔가 신기하다 생각한 v-model

 

v-model.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="http://cdn.jsdelivr.net/npm/vue"></script>
    <style>
        /* 화면에 렌더링 할 때 사용할 제목의 색상을 파란색으로 정의 */
        .blue_style {color: blue}
    </style>
</head>
<body>
    <div id="main">
        <p>{{sMsg}}</p>
        <!-- v-model은 데이터를 가져오는 동시에 입력이 동기화됨 -->
        <!-- v-bind와 v-model의 차이점 -->
        <!-- v-bind는 단방향 데이터 바인딩이고 -->
        <!-- v-model은 양반향 데이터 바인딩 -->
        <input v-model:value="sMsg">
    </div>
    <script>
        Vue.config.devtools=true;
    var main = new Vue({
        el : '#main',
        data : {
            sMsg : 'input에 글자를 입력하면 위에도 같이 바뀝니다.'

        }
    });
    </script>

</body>
</html>

 

v-model은

디렉티브를 사용하여 폼 input과 textarea 엘리먼트에 양방향 데이터 바인딩을 생성할 수 있습니다. 입력 유형에 따라 엘리먼트를 업데이트 하는 올바른 방법을 자동으로 선택합니다.

 

v-on.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="http://cdn.jsdelivr.net/npm/vue"></script>
    <style>
        /* 화면에 렌더링 할 때 사용할 제목의 색상을 파란색으로 정의 */
        .blue_style {color: blue}
    </style>
</head>
<body>
    <div id="app">
       <h1>{{sTitle}}</h1>
       <!-- 버튼을 누르면  fnChangeTitle 메서드로 이벤트
            핸들러 수행-->
       <button v-on:click="fnChangeTitle">ㅇㅇ</button>
       //버튼을 클릭 시  fnChangeTitle 호출, onclick과 같은 기능
    </div>
    <script>
        Vue.config.devtools=true;
    var app = new Vue({
        el : '#app',
        data : {
            sTitle: "ㅈㅇㅇ ㅎㅁㅇ ㅈ ㄲㅇ"
        },
        methods: {
            fnChangeTitle() {
                //this는 Vue 객체의 인스턴스를 가리킴
                this.sTitle = 'ㅈㄱ ㅇㅈㅇ!'
            }
            
        }
    });
    </script>

</body>
</html>

v-on은

디렉티브를 사용하여 DOM 이벤트를 듣고 트리거 될 때 JavaScript를 실행합니다.

버튼을 누르면 함수를 호출

 

 

v-for.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="http://cdn.jsdelivr.net/npm/vue"></script>
    <style>
        /* 화면에 렌더링 할 때 사용할 제목의 색상을 파란색으로 정의 */
        .blue_style {color: blue}
    </style>
</head>
<body>
    <div id="app">
        <h1>혁명이가 좋아하는 과일은?</h1>
        <ol>
            <!-- v-for를 통해서 반복문으로 aFruits 과일 배열 데이터를 가져옴 -->
            <li v-for="items in aFruits">
                <!-- aFruits 안의 항목을 하나씩 꺼내서 HTML로 렌더링 -->
                <p>{{ items.aFruitName }}</p>

            </li>
        </ol>
    </div>
    <script>
        Vue.config.devtools=true;
    var app = new Vue({
        el : '#app',
        data : {
            aFruits: [
                {aFruitName: '사과'},
                {aFruitName: '참외'},
                {aFruitName: '청포도'}
            ]
        }
    });
    </script>

</body>
</html>

for은 말그대로 반복 data 배열에 있는 과일들을 차례로 나오게

 

 

v-if.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="http://cdn.jsdelivr.net/npm/vue"></script>
    <style>
        /* 화면에 렌더링 할 때 사용할 제목의 색상을 파란색으로 정의 */
        .blue_style {color: blue}
    </style>
</head>
<body>
    <div id="app">
        <h1>{{bFlag}}</h1>
        <p v-if="bFlag == true">앞면!</p>
        <p v-else>뒷면!</p>
    </div>
    <script>
        Vue.config.devtools=true;
    var app = new Vue({
        el : '#app',
        data : {
            bFlag : Math.random() > 0.5

        }
    });
    </script>

</body>
</html>

조건부 렌더링 v-if 

 

디렉티브는 조건에 따라 블록을 렌더링하기 위해 사용됩니다. 블록은 디렉티브의 표현식이 true 값을 반환할 때만 렌더링됩니다.

 

 

 

 

'Front-End > Vue' 카테고리의 다른 글

[Vue] 기초-2  (0) 2021.07.22
  Comments,     Trackbacks