programing

다른 컴포넌트에서 App.vue에 액세스하는 방법

prostudy 2022. 7. 28. 21:03
반응형

다른 컴포넌트에서 App.vue에 액세스하는 방법

VueJs 2로 작성된 앱에서는 다음 코드를 Vue.app에 넣습니다.

export default {
  name: 'app',
  data () {
    return {
      title: 'Gestione fornitori',
      idfornitore: ''
    }
  },

  methods: {
    loadFunction (route) {
      this.$router.push(route)
    }
  }
}
</script>

자산에 액세스하고 싶다idfornitore다른 컴포넌트에서 사용:

    mounted () {
      this.$parent.idfornitore = ''
    },

또는 다음 항목도 있습니다.

    mounted () {
      var Vue = require('vue')
      Vue.app.idfornitore = ''
    },

하지만 효과가 없었어요.다른 구성 요소에서 자산에 액세스하는 올바른 방법은 무엇입니까?

잘 부탁드립니다.

  • 소품을 사용하여 부모에서 자녀로 데이터를 전달합니다.

  • 이벤트를 내보내 자식 간에 통신합니다.

Parent.vue

    <template>
      <div>
         <h2>Parent: {{idfornitore}}</h2>
         <child :idfornitore="idfornitore" @changevalue="idfornitore = $event"></child>
         //idfornitore - data sent to child from parent.
         //changevalue - event emitted from child and received by parent
      </div>
    </template>

    <script>
    import Child from './compname.vue';

    export default {
        components:{
            "child" : Child
        },
        data(){
            return {
                idfornitore : "34"
            }
        }
    }
    </script>

Child.vue

<template>
  <div>
    Child: {{idfornitore}}
    <button @click="add()">Add</button>
  </div>
</template>
<script>
export default {
       props:["idfornitore"],
       methods : {
           add(){
               this.idfornitore++; // mutating props directly will result in vuejs warning. i have used this code here to show how this works.
               this.$emit("changevalue",this.idfornitore); //cascade the update to parent
           }
       }
    }
</script>
  • 만약 당신이 소품을 통해 소통하는 것이 긴밀한 결합으로 이어진다고 느낀다면, 더 편리한 접근은 eventBus를 사용하는 것입니다.

컴포넌트 간의 통신은props또는events.

액세스하려는 컴포넌트 데이터가 하위 관계인 경우props단, 고객님의 경우 부모 데이터를 변경해야 합니다.이 목적을 위해, 당신은 다음을 방출할 수 있습니다.events. 컴포넌트(업데이트하려는 컴포넌트)가 현재 컴포넌트의 직계 부모일 경우 이벤트는 클린솔루션입니다.

그렇지 않은 경우 EventBus 패턴을 사용합니다.이 패턴을 사용하면 임의의 컴포넌트에서 이벤트를 내보내고 다른 컴포넌트에서 이벤트를 재생하고 그에 따라 변경을 적용할 수 있습니다.

https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication https://alligator.io/vuejs/global-event-bus/

EventBus 패턴은 컴포넌트 간의 통신이 더 자주 필요할 경우 매우 더러운 코드를 생성하고 디버깅을 매우 어렵게 만듭니다.

여러 컴포넌트 간의 공유 상태를 처리하려면vuex애플리케이션 상태를 관리하기 쉽고 유지보수가 용이합니다.모든 실제 Vue 어플리케이션에는 상태 관리가 필요하며, 이는 다음과 같은 방법으로 쉽게 달성할 수 있습니다.vuex(또는 기타 유사한 도구)를 사용하는 것이 좋습니다.

https://vuejs.org/v2/guide/state-management.html

https://vuex.vuejs.org/en/intro.html

언급URL : https://stackoverflow.com/questions/48319480/how-to-access-app-vue-from-another-component

반응형