본문 바로가기

파이썬/수업내용

[Python] Vue.js

ref와 reactive 사용법과 차이점

 - ref

<script setup>
import { ref } from 'vue'


let msg = ref("Good Morning");

function myclick(){
  console.log("myclick")
  msg.value = "Good Evening";
}



</script>

<template>
<span id="my_span">{{mag}}</span>
<!--<input type="button" value="CLICK" v-on:click="count='Good Evening'"/> -->
  <input type="button" value="CLICK" @click="myclick"/>
</template>
<style scoped>

</style>

새롭게 정의된 ref

Vue3 이전에는 뷰 템플릿의 DOM 또는 컴포넌트를 가리키는 속성이었지만, Vue3에서는 reactive reference를 의미합니다.

ref 사용하는 방법

  1. <script>에 import { ref } from "vue";을 임포트합니다.
  2. 변수를 선언하고 값을 ref()로 감싸줍니다.
  3. 변수 값을 변경할 때 변수.value에 변경할 값을 넣어줍니다.

ref의 장점

  1. 타입 제한 없이 사용 가능함
  2. 템플릿에서 단일 변수로 사용할 수 있음

 - reactive 

<script setup>
import {reactive} from 'vue'

n]
const data = reactive({
  msg : "Good Morning"
})

function myclick(){
  data.msg = "Good Evening"
}



</script>

<template>
<span id="my_span">{{data.msgs}}</span>
  <input type="button" value="CLICK" @click="myclick" />
</template>
<style scoped>

</style>

reactive 사용하는 방법

  1. <script>에 import { reactive } from "vue";을 임포트합니다.
  2. 변수를 선언하고 값을 reactive()로 감싸줍니다.
  3. property 값을 변경할 때 변수.property에 변경할 값을 넣어줍니다.

주의할 점

reactive는 object, array 이외에는 사용할 수 없습니다.

reactive의 장점

  1. 자바스크립트와 템플릿 사이에 일관성이 있음
  2. 반응형 변수를 많이 선언할 때 간단하게 사용 가능
  3. Vue2의 data()와 비슷함

 

 

- ref와 reactive의 차이점

  1. 타입 제한
    ref에서는 String, Number, Object 등 어떠한 타입에서도 사용할 수 있습니다.
    반면 reactive에서는 Object, array, Map, Set과 같은 타입에서만 사용할 수 있습니다.
  2. 접근 방식
    ref에서는 .value property를 붙여 접근할 수 있습니다. <templete>에서 변수를 명시할 때에는 붙일 필요가 없습니다.
    reactive에서는 .value를 붙일 필요가 없이 <templete>에서 사용하는 자바스크립트 문법처럼 사용하시면 됩니다.

 

Vue.js 예제

더보기

로또 생성하기

<script setup>
import {reactive} from 'vue'


const data = reactive({
  l1:"__",
  l2:"__",
  l3:"__",
  l4:"__",
  l5:"__",
  l6:"__"

})

function myclick(){
  let arr = [1,2,3,4,5,  6,7,8,9,10,
    11,12,13,14,15, 16,17,18,19,20,
    21,22,23,24,25, 26,27,28,29,30,
    31,32,33,34,35, 36,37,38,39,40,
    41,42,43,44,45];


  for(let i=0; i<1000; i++){
    let rnd = parseInt((Math.random()*45)+"");
    let a = arr[0];
    arr[0] = arr[rnd];
    arr[rnd] = a;
  }
  for(let i=0; i<=5; i++){
    for(let j=0; j<=5; j++){
      if(arr[i] < arr[j]){
        let a = arr[i]
        let b = arr[j]
        arr[i] =b ;
        arr[j] =a ;
      }
    }
  }
  data.l1 = arr[0]+"";
  data.l2 = arr[1]+"";
  data.l3 = arr[2]+"";
  data.l4 = arr[3]+"";
  data.l5 = arr[4]+"";
  data.l6 = arr[5]+"";
}



</script>

<template>
  <table border="1">
    <tr>
      <td>{{data.l1}}</td>
      <td>{{data.l2}}</td>
      <td>{{data.l3}}</td>
      <td>{{data.l4}}</td>
      <td>{{data.l5}}</td>
      <td>{{data.l6}}</td>
    </tr>
    <tr>
      <td colspan="6">
        <input type="button" value="로또 생성하기" @click="myclick"/>
      </td>
    </tr>


  </table>
</template>
<style scoped>

</style>

 

구구단 출력하기

<script setup>
import {reactive} from 'vue'


const data = reactive({
  txt : ""
})

function myclick(){
  let dan= document.querySelector('#it').value;
  let idan = parseInt(dan);

  data.txt = "";
  for (let i = 1; i <= 9; i++) {
    data.txt += idan +"*"+ i+ "="+(idan*i)+"<br />";
  }
}



</script>

<template>

  <table border="1">
      <tr>
          <td>출력단수</td>
          <td>
              <input type="text"  id="it"/>
          </td>
      </tr>
      <tr>
        <td colspan="2">
          <input type="button" value="출력하기" @click="myclick"/>
        </td>
      </tr>
      <tr>
        <td colspan="2">
          <div id="my_div" v-html="data.txt"></div>
        </td>
      </tr>



  </table>

</template>
<style scoped>
#it{
  width: 30px;
}
#my_div{
  height: 200px;
}
</style>

 

 

구구단 출력하기

<script setup>
import {reactive} from 'vue'


const data = reactive({
  com : "",
  result: "",
  mine : ""
})

function myclick(){
  
  let rnd = Math.random();

  if (rnd > 0.66){
    data.com = "가위";
  }
  else if(rnd > 0.33)	{
    data.com = "바위";
  }
  else{
    data.com = "보";
  }
  if (data.com == "가위" && data.mine == "가위") data.result = "비김";
  if (data.com == "가위" && data.mine == "바위") data.result= "이김";
  if (data.com == "가위" && data.mine == "보") data.result = "짐"  ;

  if (data.com == "바위" && data.mine == "가위") data.result = "짐";
  if (data.com == "바위" && data.mine == "바위") data.result = "비김";
  if (data.com == "바위" && data.mine == "보") data.result = "이김"  ;

  if (data.com == "보" && data.mine == "가위") data.result = "이김";
  if (data.com == "보" && data.mine == "바위") data.result = "짐";
  if (data.com == "보" && data.mine == "보") data.result = "비김"  ;
}



</script>

<template>
  <table border="1">
      <tr>
        <td>나</td>
        <td>
          <input  type="text" id="it_mine" v-model="data.mine"/>
        </td>
      </tr>
      <tr>
        <td>컴</td>
        <td>
          <input type="text" id="it_com" v-model="data.com"/>
        </td>
      </tr>
      <tr>
        <td>결과</td>
        <td>
          <input type="text" id="it_result" v-model="data.result"/>
        </td>
      </tr>
    <tr>
      <td colspan="2">
        <input type="button" value="게임하기" @click="myclick"/>
      </td>
    </tr>

  </table>
</template>
<style scoped>
#it_mine, #it_com, #it_result{
width: 50px;
}
</style>

 

전회번호출력하기

<script setup>
import {reactive} from 'vue'


const data = reactive({
  str_it : ""
})

//const myclick =(e)=>{
 // console.log(e.target);
//}

function myclick(e){
  let str_new = e.target.value;
  data.str_it = data.str_it+ str_new;
}

function mycall() {
  alert("Calling\n" + data.str_it);
}


</script>

<template>
  <table border="1">
    <tr>
      <td colspan="3">
        <input type="text" id="it" v-model="data.str_it"/>
      </td>
    </tr>
    <tr>
      <td><input type="button" class="it_num" value="1" @click="myclick($event)"/></td>
      <td><input type="button" class="it_num" value="2" @click="myclick($event)"/></td>
      <td><input type="button" class="it_num" value="3" @click="myclick($event)"/></td>
    </tr>
    <tr>
      <td><input type="button" class="it_num" value="4" @click="myclick($event)"/></td>
      <td><input type="button" class="it_num" value="5" @click="myclick($event)"/></td>
      <td><input type="button" class="it_num" value="6" @click="myclick($event)"/></td>
    </tr>
    <tr>
      <td><input type="button" class="it_num" value="7" @click="myclick($event)"/></td>
      <td><input type="button" class="it_num" value="8" @click="myclick($event)"/></td>
      <td><input type="button" class="it_num" value="9" @click="myclick($event)"/></td>
    </tr>
    <tr>
      <td><input type="button" class="it_num" value="0" @click="myclick($event)"/></td>
      <td colspan="2">
        <input type="button" class="btn_call" value="☎" @click="mycall"/>
      </td>
    </tr>

  </table>

</template>
<style scoped>
table{
  text-align: center;
}
#it{
  width: 120px;
  text-align: right;
}
.it_num{
  width: 35px;
}
.btn_call{
  width: 71px;
}
</style>

 

숫자게임

<script setup>
import {onBeforeMount, onBeforeUnmount, onMounted, onUnmounted, reactive} from 'vue'


const data = reactive({
  txt : "",
  str_it:"",
  com :50,

})

function myclick(){

  let imine = parseInt(data.str_it);
  let line ="";

  if (data.com > imine) {
    line += imine + "\t" + "UP" + "\n";
  } else if (data.com < imine) {
    line  += imine + "\t" + "DOWN" + "\n";
  } else {
    line  += imine + "\t" + "정답입니다." + "\n";
  }
  data.txt += line ;
  data.str_it="";
}

const myran = () => {
  data.com = parseInt(Math.random() * 99 + "") + 1;
  console.log("com", data.com);
}
myran();
onMounted(()=>{
  console.log('onMounted');
})
onBeforeMount(()=>{
  console.log('onBeforeMount');
})
onBeforeUnmount(()=>{
  console.log('onBeforeUnmount');
})
onUnmounted(()=>{
  console.log('onUnmounted');
})

</script>

<template>
  <table border="1">
    <tr>
      <td>맞출수</td>
      <td>
        <input type="text" id="it" v-model="data.str_it"/>
      </td>
    </tr>
    <tr>
      <td colspan="2">
        <input type="button" value="맞춰보기" @click="myclick" />
      </td>
    </tr>
    <tr>
      <td colspan="2">
        <textarea id="ta" >{{data.txt}}</textarea>
      </td>
    </tr>

  </table>
</template>
<style scoped>
it {
  width: 30px;
}

#ta {
  height: 150px;
}
</style>

 

 

 

'파이썬 > 수업내용' 카테고리의 다른 글

[python] Svelte-CRUD  (0) 2024.07.15
[Pytho] Svelte  (1) 2024.07.15
[Python] Node.js / intellij 설치 다운로드 및 설치하기  (0) 2024.07.11
[Python]CRUD - SPA  (0) 2024.07.10
[ Python] Flask - Ajax / Fetch / axios  (0) 2024.07.09