한 곳에 데이터를 제공하고
다른 곳에서 삽입
장점 :
거치지 않고 바로 상위 레벨에 전달 가능
상위 레벨에서 provide된것만 inject가능
이웃간 통신안됨
단점:
자주 쓰는건 아님, 어디서 받아왔는지 찾을려면 다 뒤져야함
가장 상위 앱에서 provide() 함
<template>
<div>
<active-element></active-element>
<knowledge-base></knowledge-base>
</div>
</template>
<script>
export default {
data() {
return {
topics: [
{
id: 'basics',
title: 'The Basics',
description: 'Core Vue basics you have to know',
fullText:
'Vue is a great framework and it has a couple of key concepts: Data binding, events, components and reactivity - that should tell you something!',
},
],
activeTopic: null,
};
},
provide() {
return {
topics: this.topics,
selectTopic: this.activateTopic
};
},
methods: {
activateTopic(topicId) {
this.activeTopic = this.topics.find((topic) => topic.id === topicId);
},
},
};
</script>
원래 대로라면 app.vue -> KnowledgeBase.vue -> KnowledgeGrid.vue 순으로 데이터를
넘겨줬어야 했다면 이번에는 상위 app.vue에 provide를 사용해서 바로 넘겨 줄 수 있음
<template>
<ul>
<knowledge-element
v-for="topic in topics"
:key="topic.id"
:id="topic.id"
:topic-name="topic.title"
:description="topic.description"
></knowledge-element>
</ul>
</template>
<script>
export default {
inject: ['topics'],
};
</script>
하위 앱에서는 inject으로 데이터를 받음
그리고 이벤트나 함수도 inject에 넣어서 사용할 수 있다.
<template>
<li>
<button @click="selectTopic(id)">Learn More</button>
</li>
</template>
<script>
export default {
inject: ['selectTopic'],
};
</script>
반응형
'언어 > WEB' 카테고리의 다른 글
vue form 에 쓰는 v-model (0) | 2023.10.14 |
---|---|
Vue - 전역/지역 컴포넌트, scoped, slot, 동적 컴포넌트,텔레포트 (0) | 2023.10.02 |
Vue - $emit 쓰는 법 (0) | 2023.09.29 |
Vue - props 컴포넌트간 통신하기 (0) | 2023.09.28 |
Vue - 컴포넌트 사용법 (0) | 2023.09.27 |