programing

VueJ 컴포넌트 간에 데이터를 공유하는 방법s

luckcodes 2022. 8. 8. 22:11

VueJ 컴포넌트 간에 데이터를 공유하는 방법s

매우 심플한 VueJS 앱이 있으며, 3개의 컴포넌트(로그인, Select Something, DoStuff)가 있습니다.

로그인 컴포넌트는 사용자 및 패스 입력을 위한 폼일 뿐이지만 두 번째 컴포넌트는 로그인 진행 중에 얻은 데이터를 표시해야 합니다.

한 컴포넌트에서 다른 컴포넌트로 데이터를 공유하려면 어떻게 해야 합니까?그러면 두 번째 컴포넌트로 라우팅할 때 Login 1에서 얻은 데이터를 그대로 유지할 수 있습니까?

소품 또는 이벤트 버스를 사용하여 구성 요소에서 이벤트를 내보내고 다른 구성 요소를 들을 수 있습니다.

vm.$on('test', function (msg) {
  console.log(msg)
})

vm.$emit('test', 'hi')
// -> "hi"

Vue.js의 컴포넌트는 소품이나 이벤트사용하여 서로 통신할 수 있습니다.이 모든 것은 컴포넌트 간의 관계에 따라 달라집니다.

다음의 작은 예를 들어 보겠습니다.

<template>
<h2>Parent Component</h2>
<child-component></child-component>
</template>

부모에서 자녀에게 정보를 보내려면 소품을 사용해야 합니다.

<template>
<h2>Parent Component</h2>
<child-component :propsName="example"></child-component>
</template>

<script>
export default {
 data(){
  return{
   example: 'Send this variable to the child'
  }
 }
}
</script>

자식에서 부모에게 정보를 보내려면 이벤트를 사용해야 합니다.

자 컴포넌트

<script>
 ...
 this.$emit('example', this.variable);
</script>

상위 컴포넌트

<template>
<h2>Parent Component</h2>
<child-component @example="methodName"></child-component>
</template>

<script>
export default {
 methods: {
  methodName(variable){
   ...
  }
 }
}
</script>

이 주제에 대한 자세한 내용은 vue.js 설명서를 참조하십시오.이것은 매우 간단한 소개입니다.

중첩된 구성 요소가 많은 경우 다음과 같은 작은 플러그인을 사용합니다.

Vue.use(VueGlobalVariable, {
  globals: {
    user: new User('user1'),
    obj:{},
    config:Config,
    ....
  },
});

이제 사용할 수 있습니다.$user소품이나 다른 것을 사용하지 않고 어떤 구성 요소에서도

언급URL : https://stackoverflow.com/questions/40224345/how-to-share-data-between-components-in-vuejs