fetch.js
파일 만들기export default {
install(app, options) {
app.config.globalProperties[options.pluginName || '$fetch'] = (url, opts) => {
return fetch(url, opts).then(res => res.json())
}
}
}
main.js
파일에서 플러그인 등록import { createApp } from 'vue'
import App from './App.vue'
import fetchPlugin from '~/plugins/fetch'
const app = createApp(App)
app.use(fetchPlugin, {
pluginName: '$myName'
})
app.mount('#app')
App.vue
파일<script>
created() {
this.init()
},
methods: {
async init() {
const res = await this.$myName('https://jsonplaceholder.typicode.com/todos/1')
console.log(res, 'Done!')
}
}
</script>
provide, inject
조상요소에서 중간 매개체없이 자손요소 컴포넌트로 바로 데이터를 전달하는 방법
provide
로 데이터 제공
inject
로 주입해서 사용
하지만, 반응성은 제공되지 않으므로 import { computed } from 'vue'
로 데이터를 만들어서 사용
그리고 형제관계나 조상/후손 관계가 아니라면 아래의 방법을 이용
Vuex(Store)
여러개의 컴포넌트가 통신할 수 있는 데이터를 store
폴더의 index.js
파일에서 전략적으로 관리하도록 구성
import { reactive } from 'vue'
를 사용하여 반응형 데이터로 만들어 줌
데이터의 추적이 가능하도록 index.js
파일에 변이 메서드mutations
나 state
, getters
, actions
와 같은 구조 생성하여 내부에 상태 데이터 생성
이를 최적화하여 사용할 수 있는 것이 Vuex
Vuex
Vue.js 애플리케이션에 대한 상태 관리 패턴 + 라이브러리
모든 컴포넌트에 대한 중앙 집중식 저장소 역할
예측 가능한 방식으로 상태를 변경
import { createStore } from 'vuex'
구조
state
상태에 대한 데이터
getters
상태에 의존한 데이터
mutations
데이터 수정 권한(동기) / 상태 변화 추적, commit 사용
actions
데이터 수정 처리(비동기) / 모든 로직 처리, dispatch 사용
중앙집중화 된 데이터 Store에서 Module사용
옵션 namespaced: true
설정
computed
this.$store.state.namesapce.state
this.$store.getters.namesapce.getters['namespace/getters']
methods
this.$store.commit('namesapce/mutations')
this.$store.dispatch.namesapce('namesapce/actions')