본문 바로가기

ETC

그 외 정리 등...

Vue.js 구조 - App.js

<template>
    <v-app>
      <SearchMenu
          @searchData="searchByMenu"
          :key="searchComponentKey"
      ></SearchMenu>

     <main>
       <v-container fluid class="pa-0">
         <router-view></router-view>
       </v-container>
     </main>

      <v-footer
          dark app
          padless
          class="pa-0 justify-center"
      >
          <v-card-actions>
            <v-btn
                v-for="icon in icons"
                :key="icon.icon"
                class="mx-4 white--text"
                icon @click="linkTo(icon.link)"
            >
              <v-icon size="24px" :color="icon.color">
                {{ icon.icon }}
              </v-icon>
            </v-btn>
            <v-btn @click="updateComponentKey">hello</v-btn>
          </v-card-actions>

      </v-footer>
    </v-app>
</template>
<script>

import SearchMenu from "@/views/SearchMenu";
export default {
  name: 'App',
  components: {SearchMenu},
  data: () => ({
    icons: [
      {icon:'mdi-home',link:''},
      {icon:'mdi-heart',color:'red darken-2',link:'my/wish'},
      {icon:'mdi-linkedin'},
      {icon:'mdi-instagram'},
    ],

    searchComponentKey:0,
  }),
  watch:{
    $route(){
      this.searchComponentKey+=1
    }
  },
  methods:{
    searchByMenu(data){
      this.$router.push({name:'search', query:{search:data}}).catch(()=>{})
    },
    linkTo(link){
      this.$router.push({path:'/'+link}).catch(()=>console.log("같은 페이지"))
    },
    updateComponentKey(){
      this.searchComponentKey +=1        //컴포넌트 리로드
    },
  },
  mounted() {
    this.updateComponentKey();
  }
};
</script>

<style>
</style>

 

우선 App.vue 페이지는 총 3가지 구성이 있다.

1. 모든 페이지에서 사용하는 SearchMenu 컴포넌트,

2.  라우팅 정보가 바뀌면 해당 페이지를 출력해주는 <router-view>

3. footer

 

1. Vue 리렌더링

 

1번인 메인 검색 화면에는 로그인 상태를 확인하는 프로필 사진이 존재한다.

(로그인 상태에서 클릭하면 마이페이지나 개인정보 수정 페이지로 이동가능한 dialog = true)

 

로그인이 실행되면 해당 로그인 정보를 $Store로 dispatch 후 state에 업데이트 해주고 그 정보를 상단 검색 컴포넌트에

불러오는 원리이다.

하지만 한번씩 로그인을 실행해도 프로필 사진이 변하지 않고, 기본 사진 그대로 출력되었다

이유는 data를 감지 못할때 리렌더링이 실행되지 않아서...

그래서 <router-view> 페이지 변화를 watch로 확인하여 updateComponentKey() 로 키값을 변경해 리렌더링 하였더니

로그인이나 로그아웃 할 때 프로필이 정상적으로 출력되었다!

 

 

 

2. Vuex 비동기 로직을 처리하는 action

 

프로젝트에서 Store를 사용할때 : dispatch 로 aciton 실행 > action에서 함수 처리 후 > Mutations 실행 > Mutations에서 State 변경 순으로 실행된다.

여기서 action을 사용하던 중 자꾸 순서가 이상하게 돌아가는 문제점이 있었는데 

콜백함수로 action을 작성하고 딜레이를 줘서 순서를 정해주니 정상적으로 동작하였다

 

 

12. Vuex Store ( 로그인 회원정보와 주문정보 Store )

index.js import Vue from 'vue'; import Vuex from "vuex"; import createPersistedState from 'vuex-persistedstate' import toOrderStore from "@/store/modules/toOrderStore"; import member from "@/store/..

dwc04112.tistory.com

 

 

 

1. Spring Boot 의 결제 및 결제모듈과의 통신

 

아래 코드는 Payments의 토큰을 받아오는 getAuth()

RestTemplate rt = new RestTemplate();


    // 토큰 받아오기
    private AccessToken getAuth() {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/json");
            headers.add("Accept", "application/json");

            JSONObject body = new JSONObject();
            body.put("imp_key", this.api_key);
            body.put("imp_secret", api_secret);

            HttpEntity<String> entity = new HttpEntity<>(body.toString(), headers);
            ResponseEntity<GetTokenDTO> response = rt.postForEntity(API_URL + "/users/getToken", entity, GetTokenDTO.class);

            if(response.getStatusCodeValue()!=200){
                throw new RuntimeException("Failed get Auth : HTTP error code : "
                        + response.getStatusCodeValue());
            }
            // No HttpMessageConverter "application/json" 에러때문에
            //json -> String 변환해서 호출. 받은 String 값 다시 json 으로 변환
            /*
            JSONObject rspBody = new JSONObject(response.getBody());
            JSONObject rspData = new JSONObject(rspBody.get("response").toString());

            AccessToken auth = new AccessToken();
            auth.setToken(rspData.get("access_token").toString());
            auth.setNow((Integer) rspData.get("now"));
            auth.setExpired_at((Integer) rspData.get("expired_at"));

            return auth;
             */

            return Objects.requireNonNull(response.getBody()).getResponse();



        }catch (Exception e){
            log.debug("Exception (getAuth) : "+ e);
        }
        return null;
    }

 

post 통신을 통해 아임포트 서버에서 토큰을 얻어오는 코드이다.

HttpEntity에 Josn형태의 body를 담아서 보냈더니 application/json 에러가 발생했다.

body를 String형식으로 변경 후 요청했더니 정상적으로 토근이 발급됐다

원래는 받는 형식도 String class로 받았는데 response 구조와 같이 DTO를 생성하여 Json형태로 받을 수 있었다.

(아래는 토큰을 받는 DTO)

 

@Getter
@NoArgsConstructor
@Data
public class GetTokenDTO {
    private int code;
    private String message;
    private AccessToken response;
}


.......


@Data
public class AccessToken {

    String access_token;
    int now;
    int expired_at;

    public String getToken() {
        return this.access_token;
    }
}