Vue.js_DAY1

이정찬·2023년 2월 10일
0

vue.js

목록 보기
1/4

Spring 보충

  • Intercepter를 이용하여 로그인 기능을 구현할 수 있다.

Vue.js

  • v-model 이라는 html 속성이 있다.이 속성을 이용하면 바로 특정한 요소에 접근하고, 둘이 아예 연동된다. onchange와 비슷하다.
  • v-bind, v-on 속성을 이용해도 비슷하게 사용할 수 있다. :value:input을 지정해 줘야 함에 주의한다.
<div id="app">
  <div class="container">
    <h1>{{ message }}</h1>
    <h1>{{ message2 }}</h1>
    <h1>{{ message3 }}</h1>
    <p>
      <button onclick="myFunction()">Click Me!</button>
    </p>
    <p>
      <input type="text" v-model="message2"/>
      <input type="text" v-bind:value="message3" v-on:input="updateInput"/>
    </p>
  </div>
</div>	

<script>
  var myObject = new Vue({
    el : '#app',
    data : {
      message : 'Hello Vue!',
      message2 : 'Hello Vue 2!',
      message3 : 'Hello Vue 3!',
  	},
    methods: {
      updateInput: (e) => {
        const updateText = e.target.value;
        this.message3 = updateText;
      }
  	}
  });

  let flag = true;

  function myFunction() {
  	if(flag) {
  		myObject.message = "Hello Yangssem!";
  	}else{
 		myObject.message = "Hello Vue!";		    	
  	}
  	flag = !flag;
  }
</script>
  • v-for를 이용하면, for문을 돌려 dom을 생성할 수 있다.
<ul>
  <li v-for="su in sus">{{su}}</li>
</ul>
<script>
  var myObject = new Vue({
  	el : '#app',
  	data : {
  	  sus: [11, 22, 33],
  	},
  });
</script>
  • onclick도 적용할 수 있다. 값에 접근하려면 오브젝트 이름에 먼저 접근해야 접근이 가능하고, 이것이 이루어져야 리랜더링이 된다.
  • v-on:click으로도 이벤트 할당이 가능하다.
<div id="app">
  <div class="container">
    <h1>{{ message }}</h1>
    <h1>{{ message2 }}</h1>
    <h1>{{ message3 }}</h1>
    <p>
      <button onclick="myFunction()">Click Me!</button>
    </p>
    <p>
      <input type="text" v-model="message2"/>
      <input type="text" v-bind:value="message3" v-on:input="updateInput"/>
    </p>
    <ul>
      <li v-for="su in sus">{{su}}</li>
    </ul>
    <p>
      <button onclick="btn_sus()">Click Me!</button>
    </p>
    <ol>
      <li v-for="name in names">{{name}}</li>
    </ol>
    <p>
      <button onclick="btn_names()">Click Me!</button>
    </p>
    <p>
      <button v-on:click="btn_names2">Click Me!</button>
    </p>
  </div>
</div>	

<script>
  var myObject = new Vue({
    el : '#app',
    data : {
      message : 'Hello Vue!',
      message2 : 'Hello Vue 2!',
      message3 : 'Hello Vue 3!',
      sus: [11, 22, 33],
      names: ['kim', 'lee', 'park'],
    },
    methods: {
      updateInput: (e) => {
        const updateText = e.target.value;
        this.message3 = updateText;
      },
      btn_names2: () => {
      	myObject.names = myObject.names.map(value => {return 'hello, ' + value});	
      }
    }
  });

  let flag = true;

  function myFunction() {
    if(flag) {
      myObject.message = "Hello Yangssem!";
    }else{
      myObject.message = "Hello Vue!";		    	
    }
    flag = !flag;
  }

  const btn_sus = () => {
  	myObject.sus = myObject.sus.map(value => {return value * 10});	
  }

  const btn_names = () => {
  	myObject.names = myObject.names.map(value => {return 'hello, ' + value});	
  }
</script>
  • 당연하게도 if문도 가능하다. v-if="{조건문}"으로 사용하며, v-else-if, v-else도 가능하다.

  • <template> 태그를 이용하여 랜더링 조절이 가능하다. if 구문이 true일 시 랜더링한다. v-show로도 대체 가능하다. 자주 바뀌면 v-show를 쓰는 것이 권장사항이다.
<template v-if="true">
  <h1>VueJS template</h1>
</template>
  • v-pre: 변수가 아닌 그냥 텍스트로 보여준다. 그러다가 변수가 들어오면 바뀐다.
  • v-once: 절대 바뀌지 않는 텍스트이다.
<p v-pre>{{message}}</p> <!-- 그냥 {{message}}라는 텍스트가 출력된다. -->
<p v-once>{{message}}</p> <!-- 그냥 {{message}}라는 텍스트가 바뀌지 않는다. -->

Life cycle

  • 인스턴스 생성 -> 화면에 부착 -> 내용 갱신 -> 인스턴스 소멸
  • 생성, 부착 사이에 create -> mount가 있고, 부착, 갱신 사이에 update가 있다. 갱신, 소멸 사이에 destroy 관련 함수가 실행된다. 이들은 new Vue 객체 안의 data 요소 안에 beforeCreate: {함수명}처럼 써주면 알아서 때에 맞게 동작한다.

Component

<script>

  Vue.component('wordRelay', {
    template: document.getElementById("temp"),
    props: ['startWord'],
    data() {
      return {
        currentWord: this.startWord,
        answerText: '호랑이',
        msg: ''
      }
    },
    methods: {
    onSubmitForm(e) {
      e.preventDefault();
      console.log(this.currentWord[this.currentWord.length - 1]);
      console.log(this.answerText[0]);
      if (this.answerText.length > 0 && this.currentWord[this.currentWord.length - 1] === this.answerText[0]) {
        this.msg = "통과";
        this.currentWord = this.answerText;
        this.answerText = '';
      }
      else if (this.answerText.trim() == 0) {
      	this.msg = "입력후 제출";
      }
      else {
        this.msg = "땡~";
        this.answerText = '';
      }
      this.$refs.target.focus();//인풋박스 포커싱에 쓰인다.
      }
    }
  });
</script>
<div id="app">
  <h1>끝말잇기~</h1>
  <word-relay start-word="홍길동" style="color: yellow"></word-relay>
</div>
  • 이런식으로 Vue.component를 이용하여 커스텀 컴포넌트를 만들 수 있고, 이를 dom처럼 사용할 수 있다.
@Configuration
public class CorsConfig implements WebMvcConfigurer {

	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/api/**").allowedOrigins("*").allowedMethods("GET","POST", "HEAD", "PUT","DELETE", "OPTIONS", "PATCH")
        .allowedHeaders("Content-Type","X-Requested-With","accept", "Origin",
                "Access-Control-Request-Method","submissionid")
        .exposedHeaders("Access-Control-Allow-Headers", "Access-Control-Allow-Origin",
                "Access-Control-Allow-Credentials").maxAge(3600L);
	}
	
}
  • WebMvcConfigurer를 상속받아 오버라이딩하면 cors 문제를 해결할 수 있다. (비동기 통신에 필요)
profile
개발자를 꿈꾸는 사람

0개의 댓글