https://ui.toast.com/weekly-pick/ko_20190430

 

앱 테마 구현 - Vue.js와 스타일드 컴포넌트로 실시간 테마 구현하기

Vue.js 프로젝트를 진행하면서 구현하기 조금 까다로웠던 기능이 있다. 완벽한 Vue 문서(Docs)만으로 바로 답을 찾을 수 없었던 부분이 있었는데, 고객 요구 사항으로 사용자 프로필에 대한 테마를

ui.toast.com

 

반응형

Typeit

https://www.typeitjs.com/

 

TypeIt

The most versatile JavaScript typewriter effect library on the planet.

www.typeitjs.com

 

Scrollout

https://scroll-out.github.io/

 

ScrollOut

Effects and CSS Vars on Scroll!

scroll-out.github.io

 

anime.js

css속성, css transform, SVG와  DOM요소의 속성, Javascript객체를 사용하여 동작하는 Javascript 애니메이션 라이브러리. 

설치 및 Import

npm install animejs --save
import anime from 'animejs/lib/anime.es.js';
<template>
  <div class="container">
  	<p class="target">target anime</p>
  </div>
</template>

export default {
	mounted() {
      this.$anime({
        targets: '.target',
        translateX: '50px',
        duration: 3000
      })
   	}
}

 

https://github.com/juliangarnier/anime

 

GitHub - juliangarnier/anime: JavaScript animation engine

JavaScript animation engine. Contribute to juliangarnier/anime development by creating an account on GitHub.

github.com


GSAP

GreenSock에서 만든 자바스크립트 애니메이션 라이브러리로 

복잡한 애니메이션을 구현하기위한 도구. 

https://greensock.com/gsap/

 

GSAP

Timeline Tip: Understanding the Position Parameter The secret to building gorgeous sequences with precise timing is understanding the super-flexible "position" parameter which controls the placement of your tweens, labels, callbacks, pauses, and even neste

greensock.com

 

반응형
// router/index.js
export default new VueRouter({
    routes: [
        {
          path: "/portfolio/blog",
          component: () => import("@/views/BlogPage.vue"),
          beforeEnter() {
            window.location.href = "https://kang-ji.tistory.com";
          },
        },
    ]
})
// views/BlogPage.vue

<template>
  <div class="blog-main">blog</div>
</template>

<script>
//import { SidebarMenu } from 'vue-sidebar-menu'

export default {
  created() {
    window.location.href = "https://kang-ji.tistory.com";
  },
};
</script>
// 컴포넌트
<template>
 <router-link tag="button" class="btn trn" to="/portfolio/blog">Blog</router-link>
</template>

외부링크로 이동

 

반응형

 

주의: mask-image는 ie 브라우저 미지원!!! 

 

mixins.scss

// mixin
@mixin svg($path, $width, $height, $color) {
	width: $width;
    height: $height;
    background-color: $color;
    -webkit-mask-image: url($path);
    mask-image: url($path);
    background-size: cover;
    -webkit-background-size: cover;
    mask-size: contain;
    -webkit-mask-position: center;
    mask-position: center;
    -webkit-mask-repeat: no-repeat;
    mask-repeat: no-repeat;
}

 

사용하기 (@include)

// 노랑색 배경의 검정 로고
.logo {
	width: 92px;
    height: 92px;
	background: #ffe31d;
    span {
    	@include svg('~@/assets/images/logo.svg', 78%, 21px, #000);
    }
}

 

호환성

https://caniuse.com/svg-css

 

SVG in CSS backgrounds | Can I use... Support tables for HTML5, CSS3, etc

Method of using SVG images as CSS backgrounds

caniuse.com

 

반응형

css를 사용하여 3D를 만들수 있다.

perspective 속성을 사용하여 원근감을 적용시켜준다.

perspective 속성

perspective 속성은 3D 위치 요소에 약간의 원근감을 주기 위해 z=0 평면과 사용자 사이의 거리를 결정한다.

transform 효과를 주고자하는 부모 요소에 적용.

  • perspective 에 따른 변형 호과
    • perspective가 클수록 (거리가 멀수록) 변형 효과가 적음
    • perspective가 작을수록(거리가 가까울수룩) 변형 효과가 큼
/* Keyword value */
perspective: none;

/* <length> values */
perspective: 20px;
perspective: 3.5em;

/* Global values */
perspective: inherit;
perspective: initial;
perspective: revert;
perspective: revert-layer;
perspective: unset;

 

예제

<div class="card-form">
    <div class="card">A</div>
    <div class="card">B</div>
    <div class="card">C</div>
</div>

 

 

공간에서 보는 시점에서 3D효과를 주게되면 각각의 카드가 원근감에따라 다르게 나타난다.

.card-form {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60vw;
    height: 60vh;
    background: #fff000;
    perspective: 500px;
}
.card {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 150px;
    border-radius: 0.5em;
    font-size: 1.5rem;
    background: #14bb8a;
    transform: rotateY(45deg);
}

 

회전되는 요소 자체에 3D효과를 주려면 아래예제 코드처럼 카드요소의 transform안에서 perspective 속성을 부여해준다.

.card-form {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60vw;
    height: 60vh;
    background: #fff000;
}
.card {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 150px;
    border-radius: 0.5em;
    font-size: 1.5rem;
  	background: #14bb8a;
    transform: perspective(500px) rotateY(45deg);
}

카드 뒤집기 예제

transform-style 속성 사용 (IE미지원)

See the Pen Untitled by KangJi (@Kangjii) on CodePen.

 

 

transform-style

요소의 자식이 3D 공간에 배치되는지 또는 요소 평면에서 병합되는지 여부를 설정한다.

ie 미지원

transform-style: flat; /* 요소의 자식이 요소 자체의 평면에 있음 */
transform-style: preserve-3d; /* 요소의 자식이 3D 공간에 배치 */

 

backface-visibility

-webkit-backface-visibility: hidden;
backface-visibility: hidden;

 

최종 (IE, Safari 지원)

See the Pen Untitled by KangJi (@Kangjii) on CodePen.

 

https://developer.mozilla.org/ko/docs/Web/CSS/backface-visibility

 

backface-visibility - CSS: Cascading Style Sheets | MDN

CSS backface-visibility 속성은 요소의 뒷면이 사용자를 향할 때 보여야 하는지 지정합니다.

developer.mozilla.org

 

 

https://developer.mozilla.org/en-US/docs/Web/CSS/transform-style

 

transform-style - CSS: Cascading Style Sheets | MDN

The transform-style CSS property sets whether children of an element are positioned in the 3D space or are flattened in the plane of the element.

developer.mozilla.org

 

반응형

1. image-rendering

이미지 랜더링 방식을 바꾼다.

원본이미지 사이즈를 그래도 사용하면 상관없지만 해당 이미지를 확대, 축소할 경우 효과를 볼 수 있다. 

크롬, 사파리 등 브라우저에서 대비를 최적화하여 이미지 랜더링을 하는데 흐린 문제를 해결해줌.

image-rendering: -moz-crisp-edges; /* firefox */
image-rendering: -o-crisp-edges; /* opera */
image-rendering: -webkit-optimize-contrast; /* chrome */
image-rendering: crisp-edges;

 

2. translateZ

z축을 0으로 적용하여 깊이감을 없앤다. 

transform: translateZ(0);

 

3. backface-visibility

뒷면을 hidden처리하여 입체감을 없앤다.

backface-visibility: hidden;

 

반응형

1. Repository 생성

2. 생성해준 저장소에서 Settings > Pages(GitHub Pages) > Source 기존 None을 Main으로 변경 , 기존 Root를 /docs 로 선택 후 Save 저장

 

3. 저장해주면 아래 처럼 url이 세팅됨. 

 

Code 로 돌아가서 Open with Github Descktop 선택 

GithubDesktop.exe 열기

 

 

 

npm run serve 로 프로젝트 실행 

 

 

 

 

 

vue.config.js

module.exports = {
  publicPath: "/portfolio/",
  outputDir: "docs",
};

npm run build를 해준다,

npm run build

npm run build 결과 설정해준 docs폴더내에 컴파일된 파일들이 생성되는 것을 확인 할 수 있다. 

 

이후 Push 하기  터미널에서 아래 순서대로 실행 

git add .
git commit -m "코멘트입력"
git push -u origin main

 

 

 

 

반응형

Vue-cli 프로젝트 생성

 

Vue-cli 설치가 되어있지 않을 경우 전역에 vue/cli 설치해주기

npm install -g @vue/cli

 

 

 

Default ([Vue 2]) 또는 Manually select features(선택하여 설치) 선택하기

Vue3는 안정화되지 않아 추후 의존성 에러 등의 문제를 발생키실 수 있다. 

 

Manually select features 선택시 체크항복

 

2.X 버전 선택

 

CSS 전처리기 선택

 

ESLInt + Prettier 선택

 

Lint on save

 

Lint on save

 

In dedicated config files 각각 별도세팅

 

설치 완료 후 프로젝트 실행하기

cd 프로젝트명
npm run serve

 

 

반응형

https://vuejsexamples.com/tag/carousel/

 

Carousel - Vue.js Examples

vue-agile Carousel component for Vue.js inspired by Slick. More powerfull with each version, touch-friendly, written in Vue and Vanilla JS (without jQuery dependency). Live Demo https://lukaszflorczak.github.io/vue-agile/ Installation yarn 20 September 201

vuejsexamples.com

https://codepen.io/alvarotrigo/pen/zpQmwq

 

vue-fullpage Issue #103

...

codepen.io

https://splidejs.com/#02

 

Splide - The lightweight, flexible and accessible slider/carousel

Splide is a lightweight, flexible and accessible slider/carousel, written in TypeScript. No dependencies, no Lighthouse errors

splidejs.com

https://antonreshetov.github.io/vue-glide/

 

Vue Glide

 

antonreshetov.github.io

 

반응형

actions 속성을 이용한 로그인 기능 구현과 비동기 처리시 유의할 점

 

SubmitForm 을 실행했을때 데이터를 요청하고 store를 이용하여 컨트롤 되고있는 상태인데 

로그인 이후의 처리로 인해 컴포넌트 단의 코드가 많아짐. 

컴포넌트단(비지니스로직이 많이 노출되지않도록) 코드를 최대한 깔끔하게 하기위한 리팩토링 

 

다른파일에 코드를 옮기는방법

1. store/index.js 에 actions를 이용해서 로그인폼 컴퍼넌트에 있는 로직들을 가져올건데 

우선 actions를 넣어주고 LOGIN함수를 만들고 

api/index.js 의 loginUser를 import 해주고 actions에 loginUser를 호출한다. 

LoginForm에서 로그인처리 로직들을 복사하여 store/index.js actions LOGIN안에 넣는다.

 

// store/index.js
import { loginUser } from '@/api/index.js';

export default new Vuex.Store({
  state: {
  ...
  },
  getters: {
   ...
  },
  mutations: {
   ...
  },
  actions: {
    LOGIN({ commit }) {
		loginUser();
    },
  },
});

 

 

 

반응형

로그인한 상태를 구현 후 발생한 문제점

로그인 후 메인화면으로 진입한 상태

 

새로고침시 에러발생 - 로딩 스피너와 상단 로그인,회원가입 이뜨며 초기상태로 되는 문제

에러구문을 살펴보면 

로그인 후 메인페이지 진입을 해서 posts 요청을 날리게 되는데 
개발자 도구의 Network > posts 를 보면 Authorization 의 속성이 비어있다. 

이러한 오류가 발생했던 이유는 

 

구현시 javascript레벨에 저장을 하고 있었고

새로고침을 하게 되면서 vue의 Store에 저장해뒀던 빈문자열 (초기화) 값이 찍히면서 

로그인시 저장되었던 token과 username 값이 사라지게 되면서 초기상태로 돌아가버렸던 것. 

 

Cookie(쿠키)를 사용하여 문제해결

로그인 인증 값 브라우저 저장소에 저장 후 확인

컴포넌트 파일에서 로그인하고나서 토큰과 username을 저장하고 router도 연결해준 상태.

 

javascript레벨에 저장하는 것 뿐만 아니라 브라우저 저장소를 이용해서 토큰 값을 저장해놓으면

새로고침을 하더라도 브라우저 저장소에서 해당값을 꺼내와 사용할 수 있게된다.

쿠키(cookie)에 정의된 함수들을 사용해보자 .

 

cookie를 setup 하는 방법
- document.cookie 를 통해 문자열을 넣어준다.
- til_auth, til_user를 이용해서 쿠키 값을 저장해오고 꺼내오도록 세팅하기

 

utils/cookies.js 

 

LoginForm.vue 에서 아래와 같이 cookies.js에 정의됬던

saveAuthToCookie(), saveUserToCooke() 함수를 import 하고 method내 비지니스 로직 안에 해당 함수를 호출한다.

이제 cookie에 token 과 username을 저장한 상태가 되는데  

이때 cookie가 저장된 것을 확인하는 방법은

서버를 실행한 후 브라우저 개발자도구 >  Application 패널 > Storage > Cookies > http://localhost:8080

에 원하는 값이 저장되는걸 확인할 수 있다. 

쿠키 API를 이용해서 브라우저 저장소에 token 과 username을 저장했다.

하지만 새로고침 했을때 여전히 문제가 발생하는데

이유는 앞써 확인한 브라우저 저장소인 cookie에 저장된 값이 Vue의 Store에 연결되지 않았기 때문..

 

 

cookie(쿠키)에 저장된 값을 Vue의 Store에 가져오기 위한 작업. 

- store/index.js 파일에서 보면 state에 username과 token이 빈문자열로 초기화되는 상태

- cookie.js에 정의된 함수중 getAuthFromCookie(), getUserFromCookie() 함수를 활용한다. 

&amp;amp;amp;amp;amp;nbsp;

store/index.js 

- cookies.js에 정의되 있는 함수 getAuthFromCookie(), getUserFromCookie() 를 import 

- state에 빈문자열이였던 token과 username값에 or 연산자를 사용하여 쿠키 함수를 추가

- 매번 Store를 생성할때마다 쿠키값을 꺼내와서 넣어보고 없으면 빈값의 문자열(초기화)

 

완료 후 실행결과

 


utils/cookies.js 본문

// utils/cookies.js

function saveAuthToCookie(value) {
  document.cookie = `til_auth=${value}`;
}

function saveUserToCookie(value) {
  document.cookie = `til_user=${value}`;
}

function getAuthFromCookie() {
  return document.cookie.replace(
    /(?:(?:^|.*;\s*)til_auth\s*=\s*([^;]*).*$)|^.*$/,
    '$1',
  );
}

function getUserFromCookie() {
  return document.cookie.replace(
    /(?:(?:^|.*;\s*)til_user\s*=\s*([^;]*).*$)|^.*$/,
    '$1',
  );
}

function deleteCookie(value) {
  document.cookie = `${value}=; expires=Thu, 01 Jan 1970 00:00:01 GMT;`;
}

export {
  saveAuthToCookie,
  saveUserToCookie,
  getAuthFromCookie,
  getUserFromCookie,
  deleteCookie,
};
반응형

 

로그인 후 아래의 전환된 화면에서 새로고침을 하게되면 

콘솔에러가 발생.

로딩스피너가 계속 돌면서  에러에 대한 처리가 안되어있는 상태 

로그인후 메인페이지 진입을 해서 posts 요청을 날리게 되는데 

Network > posts 를보면 Authorization 의 속성이 비어있다. 

로그인한 상태를 javascript레벨에 저장을 하고있었고

아래와 같이 vue Store에 state값을 저장해 둿었다.

 

하지만 당연히 새로고침을 하게되면서 refresh상태가 되기때문에 token과 username이 사라지게 되면서

해당 페이지로 다시 진입할때 로그인이 다시 필요해지며 API요청도 먹통이 된다. 

이런부분들을 쿠키로 처리해보자.

 

 

 

 

2. 로그인 인증 값 브라우저 저장소에 저장 후 확인

 

컴포넌트 파일에서

로그인하고나서 토큰과 username을 저장하고 router도 연결해준 상태.

javascript레벨에 저장하는 것 뿐만 아니라 브라우저 저장소를 이용해서 토큰값을 저장해놓으면

새로고침을 하더라도 브라우저 저장소에서 해당값을 꺼내와 사용할수 있게된다.

쿠키에 정의된 함수들을 사용해보자 .

cookies.js 정의된 함수 

cookie를 setup하는 방법

document.cookie 를 통해 문자열을 넣어주면 된다.

til_auth, til_user를 이용해서 쿠키 값을 저장해오고 꺼내오는 작업을 

 

// utils/cookies.js

function saveAuthToCookie(value) {
  document.cookie = `til_auth=${value}`;
}

function saveUserToCookie(value) {
  document.cookie = `til_user=${value}`;
}

export {
  saveAuthToCookie,
  saveUserToCookie,
};

 

로그인폼으로 돌아와 아래와 같이

cookie 함수 2개를 컴포넌트파일에 import하고 비지니스 로직안에 해당 함수를 호출한다. 

그렇게하면 cookie에 token 과 username을 저장한 상태가 된다. 

// LoginForm.vue

import { saveAuthToCookie, saveUserToCookie } from '@/utils/cookies';
export default {

 methods: {
    async submitForm() {
      try {
        // 비즈니스 로직
        const userData = {
          username: this.username,
          password: this.password,
        };
        ...
        saveAuthToCookie(data.token);
        saveUserToCookie(data.user.username);
      
      } catch (error) {
       ...
      } finally {
        ...
      }
    },
    ...
  },
}

 

cookie가 저장된것을 확인하는 방법

서버를 질행한 후 개발자도구 > Application 패널 > Storage > Cookies > http://localhost:8080

에 원하는 값이 저장되는걸 확인한다. 

쿠키 API를 이용해서 브라우저 저장소에 토큰값과 유저네임을 저장했다.

 

새로고침 했을때 여전히 문제가 발생하는데 이유는

앞써 확인한 쿠키에 저장된 값이 Vue의 Store에 연결이 되어있지 않았기 때문이다.

 

 

store/index.js 파일을 확인해보면

state에 username과 token이 빈문자열로 초기화 되는 상황.

해결방법은 cookies.js 에 있는 쿠키 함수 중 

getAuthFromCookie(), getUserFromCookie() 함수를 가져와서

저장된 값을 store/index.js에 활용한다. 

&nbsp;

store/index.js 

cookies.js파일에 있는  getAuthFromCookie(), getUserFromCookie() 를  연결해준다. 

state에 빈문자열이였던 token과 username값에 or연산자를 사용하여 

매번 Store를 생성할때마다 쿠키값을 꺼내와서 넣어보고 없으면 빈값의 문자열(초기화)

 

 

 

 

이를 해결하기위해 쿠키를 설정해줍니다.

// utils/cookies.js

function saveAuthToCookie(value) {
  document.cookie = `til_auth=${value}`;
}

function saveUserToCookie(value) {
  document.cookie = `til_user=${value}`;
}

function getAuthFromCookie() {
  return document.cookie.replace(
    /(?:(?:^|.*;\s*)til_auth\s*=\s*([^;]*).*$)|^.*$/,
    '$1',
  );
}

function getUserFromCookie() {
  return document.cookie.replace(
    /(?:(?:^|.*;\s*)til_user\s*=\s*([^;]*).*$)|^.*$/,
    '$1',
  );
}

function deleteCookie(value) {
  document.cookie = `${value}=; expires=Thu, 01 Jan 1970 00:00:01 GMT;`;
}

export {
  saveAuthToCookie,
  saveUserToCookie,
  getAuthFromCookie,
  getUserFromCookie,
  deleteCookie,
};

cookies.js에 정의해둔 함수를 이용해 연결해준다.

 

 

 

 

 

 

 

 

로그인 을 성공하여 전환된 화면에서 새로고침을 했을때 

 

 

 

개발자도구 > Application > Cookies 에서 오류발생 

 

로그인 인증 값 브라우저 저장소에 저장

 

// LoginForm.vue
import { saveAuthToCookie, saveUserToCookie } from '@/utils/cookies';

export default {
  data() {
    return {
      // form values
      username: '',
      password: '',
      // log
      logMessage: '',
    };
  },
  computed: {
    isUsernameValid() {
      return validateEmail(this.username);
    },
  },
  methods: {
    async submitForm() {
      try {
        // 비즈니스 로직
        const userData = {
          username: this.username,
          password: this.password,
        };
        const { data } = await loginUser(userData);
        console.log(data.token);
        this.$store.commit('setToken', data.token);
        this.$store.commit('setUsername', data.user.username);
        saveAuthToCookie(data.token);
        saveUserToCookie(data.user.username);
       
      } catch (error) {
        // 에러 핸들링할 코드
        console.log(error.response.data);
        this.logMessage = error.response.data;
      } finally {
        this.initForm();
      }
    },
    initForm() {
      this.username = '';
      this.password = '';
    },
  },
};

 

개발자도구 > Application > Storage > Cookies

 

 

 

개발자도구 > Vue > Switch to Vuex(반시계아이콘) > Base State 클릭

아래의 State token값이 빈값.

쿠키에 저장된 값이

Vue Store에 연결이 되어있지 않다. 

 

 

 

util/cookies.js 함수

saveAuthToCookie, saveUserToCookie 를 통해 저장을 했다. 

쿠키에서 값을 가져올때 

getAuthFromCookie(), getUserFromCookie() 함수를 이용해서

저장된 값을 Store의 index.js에서 활용해주는작업

 

 

매번 Store를 생성할때마다 쿠키값을 꺼내와서 넣어보고 없으면 빈값의 문자열(초기화)

// store/index.js

import Vue from 'vue';
import Vuex from 'vuex';
import { getAuthFromCookie, getUserFromCookie } from '@/utils/cookies';

export default new Vuex.Store({
  state: {
    username: getUserFromCookie() || '',
    token: getAuthFromCookie() || '',
  },
 
});

 

실행결과

 

store/index.js 에도 cookie 함수 연결해주기

반응형

서버로 요청을 보내는것과 서버에서 받은 응답을 화면(컴포넌트)단에서 처리하기전에

추가로직을 넣을수 있는 API

 

인터셉터를통해 token을 실어보낼 수 있다.

 

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // 요청보내기 전 코드
    return config;
  }, function (error) {
    // 요청에러 처리
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // 응답을 받기 전에 처리
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // 응답에러 전처리
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

 

반응형

Vuex

Vuex는 vue.js 애플리케이션을 위한 상태관리 라이브러리 
모든 컴포넌트들에 접근가능한 데이터 저장소로
컴포넌트간 공통으로 사용되는 데이터 속성을 저장한다.
Vuex는 Vue.js의 상태관리 라이브러리로 애플리케이션의 모든 컴포넌트에 대한 중앙 집중식 저장소 역할을 하며 의도적인 방법으로 상태를 변경 및 관리할 수 있다.
Vuex는 기존 React의 Flux의 아키텍처를 따라가고 있고 React로 본다면 Redux와 비교 대상으로 볼 수 있다.
Vue.js에서도 Redux를 사용할 수 있지만 Vue.js는 Vuex와의 호환이 좋을 뿐만 아니라 더 직관적으로 개발할 수 있다.

 

설치 (dependencies에 설치)

npm i vuex

 

store/index.js

//store/index.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    username: '',
  },
});

 

main.js

// main.js

import Vue from 'vue';
import App from './App.vue';
import router from '@/routes/index';
import store from '@/store/index';

Vue.config.productionTip = false;

new Vue({
  render: h => h(App),
  router,
  store,
}).$mount('#app');

 

npm run serve

 

크롬 Vue개발자도구

 


Vuex 구조

Vuex는 state, mutations, action, getters 4가지 형태로 관리가 되며,

이때 이 관리 포인트는 store 패턴을 사용하고 통상 store라고 불린다.

이 4가지는 서로간의 간접적으로 영향이 있으며 단방향 데이터 흐름으로 볼 수 있다.

 

1. State

  • 컴포넌트 간에 공유하는 데이터 = data() { ... }
  • Vue 컴포넌트에서 data로 볼 수 있다. 원본 소스의 역할을 하며, View와 직접적으로 연결되어있는 Model이다. 이 state는 직접적인 변경은 불가능하고 mutation을 통해서만 변경이 가능하다. mutation을 통해 state가 변경이 일어나면 반응적으로 View가 업데이트된다.

2. Mutations

  • 동기로직 
  • state를 변경하는 유일한 방법이고 이벤트와 유사하다. mutation은 함수로 구현되며 첫 번째 인자는 state를 받을 수 있으며, 두 번째 인자는 payload를 받을 수 있다. 여기서 payload는 여러 필드를 포함할 수 있는 객체형태도 가능하다. 이 mutation은 일반적으로(Helper를 쓰지 않는 경우)는 직접 호출을 할 수 없으며, commit을 통해서만 호출할 수 있다.

3. Actions

  • 비동기 로직 = axios
  • Action은 mutation과 비슷하지만 mutation과는 달리 비동기 작업이 가능하다. 또한 mutation에 대한 commit이 가능하여 action에서도 mutation을 통해 state를 변경할 수 있다. 
  • action에서는 첫 번째 인자를 context 인자로 받을 수 있으며 이 context에는 state, commit, dispatch, rootstate와 같은 속성들을 포함한다. 두 번째 인자는 mutation과 동일하게 payload로 받을 수 있다.
  • commit을 통해 mutation을 호출했다면 Action은 dispatch를 통해서 호출한다. context의 속성을 보면 dispatch가 있는 것으로 보아 action에서는 서로 다른 action을 호출할 수 있다는 것을 볼 수 있다.

4. Getters

  • 중복된 데이터 처리
  • Getters는 쉽게 Vue 컴포넌트에서 Computed로 볼 수 있다. 
  • 말로 풀자면 계산된 속성인데 getter의 결과는 종속성에 따라 캐시 되고 일부 종속성이 변경된 경우에만 다시 재계산된다. 
  • 즉, 특정 state에 대해 어떠한 연산을 하고 그 결과를 View에 바인딩할 수 있으며, state의 변경 여부에 따라 getter는 재계산이 되고 View 역시 업데이트를 일으킨다. 이때 state는 원본 데이터로서 변경이 일어나지 않는다.

 

반응형

dependencies 

애플리케이션 로직과 관련된 라이브러리 목록

npm run build 를 수행하게되면 dependencies 에 있는 라이브러리 목록이

포함되어  최종적인 자원이 압축(변환)이 됨.

  • axios
  • vue
  • vue-router
  • vuex

 

vuex 애플리케이션이 동작할때 필요한 라이브러리

 


devDependencies 

npm run build 의 결과물에 포함되지 않음. 

  • cli-server
  • eslint

 

반응형

+ Recent posts