es6-promise

 

 

 

 

  • es6-promise

IE는 Promise를 지원하지 않는다. 이를 해결하기 위해선 es-promise의 polyfill기능을 활성화 해야한다.

vuex나 axios를 사용하는 시점보다 빨리 불러와야 정상 동작한다.

 

// cdn
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js"></script>
 
// npm
npm install --save es6-promise            // npm
yarn add es6-promise              // yarn
 
require('es6-promise').polyfill();        // CommonJs 방식
 
import 'es6-promise/auto'                 // ES6 방식

 

 

'Vue' 카테고리의 다른 글

watch  (0) 2023.04.11
vuex  (0) 2019.02.24
vue-router  (0) 2019.02.23
axios  (0) 2019.02.23
트랜지션  (0) 2019.02.10

watch

 

https://ryuzuka.github.io/VUE/tutorial/20_watch.html

 

 

data의 변경에 반응하는 일반적인 방법, 감시자 역할을 한다.

new Vue({
data () {
return {
count: 0
}
},
watch: {
count () {
console.log( 'count - watch' )
}
},
created () {
this.$watch( 'count', function () {
console.log( 'count - watch' )
});
}
}).$mount( '#app' )

 

'Vue' 카테고리의 다른 글

es6-promise  (0) 2023.05.19
vuex  (0) 2019.02.24
vue-router  (0) 2019.02.23
axios  (0) 2019.02.23
트랜지션  (0) 2019.02.10

vuex


https://ryuzuka.github.io/VUE/tutorial/18_vuex.html


Vue.js 어플리케이션에 대한 상태 관리 패턴 + 라이브러리. (  모든 데이터( state ) 통신을 한 곳에서 중앙 집중식으로 관리한다. )

1. 여러 컴포넌트가 하나의 데이터를 공유하고 있을 때

2. 부모 - 자식 컴포넌트 간의 데이터 공유가 아닌 수평적인 컴포넌트 간의 데이터 공유가 필할때


  • 설치

npm install vuex --save       // 설치 ( 또는 vue-cli setting )

import Vuex from 'vuex'    // import

Vue.use( Vuex );                // 모듈 시스템과 함께 사용하려면 Vue.use()를 통해 명시적으로 추가해야 한다.


  • $store ( 상태관리 패턴 )

- state : 컴포넌트 간 공유될 data

- view : 데이터가 표현될 template

- actions : 사용자의 입력에 따라 반응할 methods


  • state

Vuex의 애플리케이션 상태를 보유하고 있는 컨테이너. 저장소의 상태가 변경되면 효율적으로 대응하고 업데이트 한다.

Vue.use( Vuex )로 인해 모든 자식 컴포넌트에 저장소를 주입 할 수 있다. - this.$store 접근 가능

( 컴포넌트의 data 역할 )

const store = Vuex.Store({
state: {
count: 0                                         // state 는 컴포넌트 간에 공유되는 data 속성을 의미한다.
}
})

new Vue({
el: '#vuex',
store: store,                             // 저장소 주입     
computed: {
count () {
return this.$store.state.count                      // computed를 통해 $store의 state 사용
},

}
})


  • getters

각 컴포넌트에서 수행 로직을 호출하고 Vuex에서 state 변경이 이루어지도록 하는 역할을 한다.

( 컴포넌트의 computed 역할 )

const store = new Vuex.Store({
getters: {
getCount: ( state, getters ) => state.count + 1        // state와 getters를 인자로 받는다.
}
})

new Vue({
computed: {
increasedCount () {
return this.$store.getters.getCount
},
}
})


  • mapGetters

getters의 저장된 속성을 mapGetters를 활용하여 간편하게 사용할 수 있으며 vuex 에서 관리 된다.

import { mapGetters } from 'vuex'

new Vue({

computed: {
// 컴포넌트 자체의 coupute에 정의된 속성과 함께 사용하기 위해 ES6문법 ...을 사용한다.
...mapGetters( ['getCount'] ), // getters의 옵션을 배열로 선언하여 간단하게 사용
...mapGetters({ // getters의 옵션을 객체로 선언하여 직관적으로 사용
mapGetCount: 'getCount'
})
}
})


  • mutations

vuex의 state 값을 변경하는 로직 ( mutations가 낯설다면 기억하기 쉽게 setters로 이해할 수 있다. )

1. 동기 처리 로직 정의 ( actions - 비동기 처리 로직 정의 )

2. commit을 이용하여 state를 변경한다. ( 컴포넌트에서 직접 state에 접근하여 변경 - anti 패턴 )

const store = new Vuex.Store({
mutations: {
setCount: ( state, payload ) => state.count += 1 // 데이터 인자 명은 보통 payload 를 많이 쓴다.
}
})

new Vue({
methods: {
increaseCount () {
this.$store.commit( 'setCount', {} )
}
}
})


  • mapMutations

mapGetters 와 마찬가지로, Vuex 에 내장된 mapMutations 를 이용하여 코드 가독성을 높일 수 있다.

import { mapMutations } from 'vuex'

new Vue({
methods: {
// 컴포넌트 자체의 methods에 정의된 속성과 함께 사용하기 위해 ES6문법 ...을 사용한다.
...Vuex.mapMutations( ['setCount'] ), // getters의 옵션을 배열로 선언하여 간단하게 사용
...Vuex.mapMutations({ // getters의 옵션을 객체로 선언하여 직관적으로 사용
mapSetCount: 'setCount'
})
}
})


  • actions

actions는 비 순차적 또는 비동기 처리 로직들을 선언한다. state의 변경을 추적하기 위해 결국 mutations의 method를 commit하는 구조가 된다.

1. 동기 처리 로직 정의 ( mutations - 동기 처리 로직 정의 )

2. payload, object 스타일의 dispatch를 지원한다.

const store = new Vuex.Store({
actions: {
increase ( context ) {                                  // actions == commit ==> mutations
context.commit( 'setCount', { amount: 10 } ) // payload style

context.commit({ // object style
type: 'setCount',
amount: 10
})
}
}
})

new Vue({
methods: {
increaseCount () {
this.$store.dispatch( 'increase' )
}
}
})


  • mapActions

mapGetters, mapMutations 헬퍼 함수들과 마찬가지로 mapActions 도 동일한 방식으로 사용할 수 있다.

import { mapActions } from 'vuex'

new Vue({
methods: {
// 컴포넌트 자체의 methods에 정의된 속성과 함께 사용하기 위해 ES6문법 ...을 사용한다.
...Vuex.mapActions( ['increase'] ), // getters의 옵션을 배열로 선언하여 간단하게 사용
...Vuex.mapActions({ // getters의 옵션을 객체로 선언하여 직관적으로 사용
mapSetCount: 'increase'
})
}
})


'Vue' 카테고리의 다른 글

es6-promise  (0) 2023.05.19
watch  (0) 2023.04.11
vue-router  (0) 2019.02.23
axios  (0) 2019.02.23
트랜지션  (0) 2019.02.10

vue-router


https://ryuzuka.github.io/VUE/tutorial/17_vue-router.html


라우팅 기능을 구현할 수 있도록 지원하는 공식 라이브러리


  • 설치

npm install vue-router --save       // 설치 ( 또는 vue-cli setting )

import VueRouter from 'vue-router'    // import

Vue.use( VueRouter )                      // 모듈 시스템과 함께 사용하려면 Vue.use()를 통해 명시적으로 추가해야 한다.


  • VouRouter

// 필수 엘리먼트
<router-link to="/"></router-link>        // 페이지 이동 엘리먼 ( 화면에서는 <a></a>로 표시됨 )

<router-view></router-view>               // 페이지 표시 엘리먼트 - 해당컴포넌트가 화면에 표시되는 영역


let router = new VueRouter({              // 생성
mode: 'history',              // url의 hash값을 없앤다.
    routes: [                             // 각 라우트는 반드시 컴포넌트와 매핑되어야 한다.
...
]
});

new Vue({
router: router                         
}).$mount( '#router' ) // $mount: el 속성과 동일하게 생성된 인스턴스를 화면에 붙이는 역할을 한다.


  • mode: 'history'

history mode : url의 hash( #태그 ) 값을 제외하고 기본 URL 방식을 사용한다.

( vue-router의 기본 모드는 hash mode 이다. )


  • .redirect
{ path: '/...', redirect: { name: '' } }    // 이름이 지정된 라우트를 지정할 수도 있다.
{ path: '/*', redirect: '' }                // '/*': 해당 router에 정의 되어있지 않는 path 일때


  • 동적 라우트 매칭 ( /: )

 동일한 라우트에 여러 동적 세그먼트를 가질 수 있으며, $route.params  접근 할 수 있다.

패턴일치하는 패스$route.params
/user/:username/user/evan{ username: 'evan' }
/user/:username/post/:post_id

/user/evan/post/123

{ username: 'evan', post_id: '123' }


  • 매칭 우선순위

 동일한 URL이 여러 라우트와 일치하는 경우가 있다. 이 경우 일치하는 우선 순위는 라우트 정의의 순서에 따라 결정된다. 즉, 경로가 더 먼저 정의 될수록 우선 순위가 높아진다.


  • children( 중첩된 라우트 )

<route-view>에 렌더링 된 컴포넌트 내부에는 자신의 중첩 된 <route-view>를 포함 할 수도 있다.

new VueRouter({
routes: [
{ path: '', name: '', component: '',
children: [
{ path: '', name: '', component: '' }
]
},
]
})


  • 프로그래밍 방식 네비게이션

router.push( location, onComplete, onAbort ) - onComplete, onAbort 콜백 제공

선언적 방식프로그래밍 방식
<router-link :to="...">router.push(...)
// 리터럴 string
router.push('home')

// object
router.push({ path: 'home' })

// 이름을 가지는 라우트
router.push({ name: 'user', params: { userId: 123 }})

// 쿼리와 함께 사용, 결과는 /register?plan=private 입니다.
router.push({ path: 'register', query: { plan: 'private' }})


    router.replace( location )새로운 히스토리 항목에 추가하지 않고 탐색

    선언적 방식프로그래밍 방식
    <router-link :to="..." replace>router.replace(...)


    router.go(n)window.history.go(n)와 비슷하게 히스토리 스택에서 앞으로 또는 뒤로 이동

    // 한 단계 앞으로 갑니다. history.forward()와 같습니다.
    router.go(1)

    // 한 단계 뒤로 갑니다. history.back()와 같습니다.
    router.go(-1)

    // 3 단계 앞으로 갑니다.
    router.go(3)

    // 지정한 만큼의 기록이 없으면 자동으로 실패 합니다.
    router.go(-100)
    router.go(100)




    'Vue' 카테고리의 다른 글

    watch  (0) 2023.04.11
    vuex  (0) 2019.02.24
    axios  (0) 2019.02.23
    트랜지션  (0) 2019.02.10
    사용자 정의 디렉티브  (0) 2019.02.09

    axios


    https://ryuzuka.github.io/VUE/tutorial/16_axios.html


    HTTP 요청을 위한 axios


    • 설치

    npm install --save axios     // 설치

    import Axios from 'axios'     // import

    Vue.prototype.Axios = Axios    // Vue 전역 추가 ( 또는 각 컴포넌트 별로 import )

    • axios

    new Vue({
    el: '#app',
    data: {
    posts: null
    },
    methods: {
    fetchPosts () {
    this.Axios.get( 'https://jsonplaceholder.typicode.com/posts' )
    .then(( response ) => {
    this.posts = response.data
    })
    }
    }
    })


    'Vue' 카테고리의 다른 글

    vuex  (0) 2019.02.24
    vue-router  (0) 2019.02.23
    트랜지션  (0) 2019.02.10
    사용자 정의 디렉티브  (0) 2019.02.09
    믹스인  (0) 2019.02.09