Vue js 기본

이은지·2021년 8월 15일
0

한시간만에 끝내는 Vue.js 입문
해당 영상을 개인공부 목적으로 재구성한 내용입니다.

Vue js와 라우팅

Vue js는 컴포넌트 기반 spa 원페이지 어플리케이션이다. 라우터를 이용한다.

미리 해당하는 component 페이지를 다 받아놓고 필요한 부분만 화면을 갱신하는 게 라우팅

# App.vue

<template>
  <div id="app">
    <Header />
    <div id="content" class="content">
      <router-view></router-view>
    </div>
</template>

<script>
import Header from './components/layout/Header.vue'

export default {
  name: 'App',
  components: {
    Header,
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
  • template는 사용자들이 보는 부분. 디자인적 측면. html.
    script는 서버 등이랑 연결해주거나, 이벤트를 캐치

  • script에 Header를 임포트. 그 다음에 defualt안에 components에도 써줘야 사용이 가능해짐.
    여기까지 했다면 이제 template안에서 Header를 쓸 수 있음.

    template안에서 <Header />는 한 줄에 불과하지만, 이건 vue에서 자동으로 './components/layout/Header.vue'를 참조해온 것이기 때문에 Header.vue 파일에 있는 요소들이 불러와진다.

  • 그 다음 <Header />밑에는 라우터를 넣어줘야 함!
    헤더는 더이상 바뀌지 않고, <route-view></route-view>이 사이에 넣는 컴포넌트들만 바뀌게끔 페이지를 구성할 예정

# router.js

import Vue from "vue";
import VueRouter from "vue-router";
import Home from "./views/Home";
import About from "./views/About";

Vue.use(VueRouter); #vue 내에서 라우터를 사용하겠다

const router = new VueRouter({ #라우터 정의
    mode: "history",
    routes: [{
        path:"/",
        component: Home
    },
    {
        path: "/about",
        component: About 
    } #path에 about이 들어오면 About 컴포넌트를 로딩하겠다.
    ]
});
  • routes라는 배열 안에 사용자가 들어왔을 때 어디로 넘길 것인지를 정의한다.

    path가 바뀔 때마다 Home, About 등 미리 만들어놓은 컴포넌트를 만들어서 router-view라는 곳에 불러서 로딩시키겠다. path마다 어떤 컴포넌트와 연결할지 지정.

이렇게 라우터를 만든 다음, 사용하기 위해서는 main.js에 추가해줘야 한다.

# main.js

import Vue from 'vue'
import App from './App.vue'
import Vue from 'vue'
import router from './router' # 라우터 추가 부분
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'

// Import Bootstrap an BootstrapVue CSS files (order is important)
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'

// Make BootstrapVue available throughout your project
Vue.use(BootstrapVue)
// Optionally install the BootstrapVue icon components plugin
Vue.use(IconsPlugin)

Vue.config.productionTip = false

new Vue({
  router, # 라우터 추가 부분
  render: h => h(App),
}).$mount('#app')

데이터 핸들링하기

<template>
    <div>
        <h1>Welcome to {{title}}!</h1>
    </div>
</template>
<script>
export default {
    data() {
        return {
          title: "개발자의 품격",  
          title2: "Seoul"
        };
    }
};
</script>
  • data()라는 메소드를 통해 데이터를 핸들링 한다.

data( ) { return { }} 에서 return 안에 변수를 정의한 다음,
<template>내에서 {{}} 안에 변수명을 넣음으로써 html에 해당 데이터를 바인딩할 수 있다.

<template>
    <div>
        <h1>Welcome to {{title}}!</h1>
        <input type="text" v-model="input1" />
        <button type="button" @click="getData">Get</button>
        <button type="button" @click="setData">Set</button>
    </div>
</template>
<script>
export default {
    data() {
        return {
          title: "개발자의 품격",  
          title2: "Seoul",
          input1: "abcd",
        };
    },
    methods: {
        getData() {
            alert(this.input1); 
            #메소드 안에서 데이터에 접근하기 위해서는 this. 를 꼭 써줘야 한다. 변수명만 쓰면 안된다.
            #input1이라는 변수에 바인딩되어 있는 데이터를 알림창에 띄워줘!
        },
        setData() {
            this.input1 = "12345";
            #input1에 "12345"라는 값을 셋
        },
    }
};
</script>
  • vue js는 two-way binding을 지원해준다.
    우리가 정의해놓은 데이터를 화면에 보여줄 수도 있고, 화면의 값을 메소드로 컨트롤할 수도 있다.

  • v-model: vue에서는 v-model을 사용해서 데이터를 바인딩하고 처리한다.

  • @click="" : 버튼 클릭 시 " "안의 메소드를 호출
    위 코드에서는 버튼 클릭 시 사용자의 입력을 받아오게끔 하기 위해 getData() 라는 메소드를 할당했다.

  • 모든 메소드는 methods: {} 안에 정의한다.

Vue의 라이프사이클

beforeCreate

created: 옵션 등이 설정되는 단계

beforeMount: 컴포넌트가 돔에 추가되기 직전에 실행됨

mounted: 돔에 추가된 후에 실행됨

데이터가 변경될 때마다 re-rendering이라는 게 일어나는데

beforeUpdate: 재렌더링 되기 전에 실행되는 이벤트

updated: 된 직후에 실행되는 이벤트

beforeDestroy: 컴포넌트가 제거되기 직전의 이벤트 훅

destroyed:제거 후 실행되는 이벤트 훅

<template>
    <div>
        <h1>Welcome to {{title}}!</h1>
        <input type="text" v-model="input1" />
        <button type="button" @click="getData">Get</button>
        <button type="button" @click="setData">Set</button>
    </div>
</template>
<script>
export default {
    data() {
        return {
          title: "개발자의 품격",  
          title2: "Seoul",
          input1: "abcd",
        };
    },
    watch: {
        input1() {
            console.log(this.input1);
        },
    },
    methods: {
        getData() {
            alert(this.input1);
        },
        setData() {
            this.input1="12345"; 
            },
    },
    beforeCreate() {
        console.log("beforeCreate");
    },
    created() {
        console.log("created");
    },
    beforeMount() {
        console.log("beforeMount");
    },
    mounted() {
        console.log("mounted");
    },
    beforeUpdate() {
        // console.log("beforeUpdate");
    },
    updated() {
        // console.log("updated");
    },
    beforeDestroy() {
        console.log("beforeDestroy");
    },
    destroyed() {
        console.log("destroyed");
    },    
};
</script>
  • 시점마다 우리가 필요한 코드를 작성해서 넣는다고 생각하면 된다.
    만약 처음에 페이지를 켰을 때부터 바로 사용자에게 보여져야 하는 데이터가 있다면 beforeCreate나 created 단계에 코드를 작성. 그러면 mounted시에 같이 렌더링이 된다. 사용자가 기다릴 필요가 없고, 불필요한 리렌더링이 발생하지 않을 수 있다.
  • watch: 특정 데이터가 변경되는 것을 계속 모니터링. 변경됐을 때 특정 작업을 진행하도록 할 수 있다.
    데이터에 선언한 변수명과 같은 이름으로 메소드를 만드는 방식으로 사용한다.

배열 데이터 핸들링 with v-for

<template>
    <div>
        <h1>Welcome to {{title}}!</h1>
        <input type="text" v-model="input1" />
        <button type="button" @click="getData">Get</button>
        <button type="button" @click="setData">Set</button>

        <select class="form-control" v-model="region">
            <option :key="i" :value="d.v" v-for="(d,i) in options">{{d.t}}</option>
        </select>
        
        <table class="table table-bordered" v-if="tableShow">
            <tr :key="i" :value="d.v" v-for="(d,i) in options">
                <td>{{d.v}}</td>
                <td>{{d.t}}</td>
            </tr>
        </table>
    </div>
</template>
<script>
export default {
    data() {
        return {
          title: "개발자의 품격",  
          title2: "Seoul",
          input1: "abcd",
          options: [
              {v:"S",t:"Seoul"},
              {v:"J",t:"Jeju"},
              {v:"B",t:"Busan"}
          ],
          region: "J"
          tableShow: false
        };
    },
    watch: {
        input1() {
            console.log(this.input1);
        },
    },
    methods: {
        getData() {
            alert(this.input1);
        },
        setData() {
            this.input1="12345"; 
            }, 
    }    
};
</script>
  • data()options라는 배열을 선언

  • v-for를 통해 반복문을 돌릴 수 있다.
    v-for="(d, i)" in options라고 하면 options라는 배열에서 (데이터, 인덱스)를 차례로 가져온다. 여기서 데이터라 함은 v-t 한 쌍을 의미하는 듯.

  • {{d.t}} html 상에는 데이터의 t에 해당하는 값, 즉 Seoul, Jeju, Busan을 출력. html 코드안에서 데이터에 접근할 때는 중괄호 두 개를 쓴다. 엘리먼트 안에서 바로 접근할 때는 콜론을 쓴다.

  • key를 꼭 설정해줘야 한다.

  • v-model을 통해서 selectbox에 region이라는 데이터를 바인딩. 셀렉트박스의 기본값이 Jeju가 된다. region: "B"로 바꾸면 기본값이 Busan이 됨.

<template>
    <div>
        <h1>Welcome to {{title}}!</h1>
        <input type="text" v-model="input1" />
        <button type="button" @click="getData">Get</button>
        <button type="button" @click="setData">Set</button>

        <select class="form-control" v-model="region" @change="changeRegion">
            <option :key="i" :value="d.v" v-for="(d,i) in options">{{d.t}}</option>
        </select>

        <table class="table table-bordered" v-if="tableShow">
            <tr :key="i" :value="d.v" v-for="(d,i) in options">
                <td>{{d.v}}</td>
                <td>{{d.t}}</td>
            </tr>
        </table>
    </div>
</template>
<script>
export default {
    data() {
        return {
          title: "개발자의 품격",  
          title2: "Seoul",
          input1: "abcd",
          options: [
              {v:"S",t:"Seoul"},
              {v:"J",t:"Jeju"},
              {v:"B",t:"Busan"}
          ],
          region: "J",
          tableShow: false
        };
    },
    watch: {
        input1() {
            console.log(this.input1);
        },
    },
    methods: {
        getData() {
            alert(this.input1);
        },
        setData() {
            this.input1="12345"; 
        },
        changeRegion() {
            alert(this.region);
        }
    },  
};
</script>
  • 테이블을 선언할 수도 있다. 마찬가지로 v-for를 활용하여 for문을 돌릴 수 있다.

  • tr: table row, td: table data

  • v-if: 조건에 따라 개체를 렌더링 할지 말지를 결정한다. 특정 조건에서만 보여주어야 하는 화면의 경우 v-if를 쓰는 게 리소스를 오히려 덜 잡아먹을 수 있다.

  • v-show: 렌더링은 조건 충족 여부와 상관없이 함. 단지 조건이 충족 안되면 화면에서 안보이게 하는 것. 특정 화면에서 보였다 안보였다를 자주 해야 하는 경우 v-if보다는 v-show를 쓰는 게 리소스를 훨씬 덜 잡아먹을 수 있다.

profile
교육학과 출신 서타터업 프론트 개발자 👩🏻‍🏫

0개의 댓글