Programing

다른 구성 요소의 Vue 호출 방식

c10106 2022. 5. 24. 23:05
반응형

다른 구성 요소의 Vue 호출 방식

나는 카드 컴포넌트와 모달 컴포넌트, 모달 컴포넌트가 두 개 있는데, 모달 컴포넌트는 모달 엘리먼트를 포함하고 있다. 내 카드 컴포넌트에 모달 컴포넌트의 모달 윈도우를 여는 버튼을 갖고 싶다.내가 그것을 어떻게 관리하느냐, 지금까지 나는 이렇게 했다.

내 카드 구성 요소:

<template>
    <v-layout v-if="visible">
        <v-flex xs12 sm6 offset-sm3>
            <v-card>
                <v-card-title primary-title>
                    <div>
                        <h3 class="headline mb-0">test</h3>
                        <div>test</div>
                    </div>
                </v-card-title>

                <v-divider light></v-divider>

                <v-card-actions>
                <v-btn
                    color="primary"
                    dark
                    @click="dialog = true"
                >
                Open Dialog
                </v-btn> <!-- open modal dialog of modal component? -->

                    <tenant-number-modal></tenant-number-modal>
                </v-card-actions>

                <input type="hidden" id="tenant-id" :value=tenantId>
            </v-card>
        </v-flex>
    </v-layout>
</template>

<script>
    export default {
        data () {
            return {
                visible: true,
                dialog: false,
                uniqueTenantNumber: ''
            }
        },
    }
</script>

내 모달 구성 요소:

<template>
    <v-layout row justify-center>
        <v-btn
            color="primary"
            dark
            @click="dialog = true"
        > <!-- this calls the modal but only in this component -->
        Open Dialog
        </v-btn>

        <v-dialog
            v-model="dialog"
            max-width="290"
        >
            <v-card>
                <v-card-title class="headline">test</v-card-title>
            </v-card>
        </v-dialog>
    </v-layout>
</template>

<script>
  export default {
    data () {
      return {
        dialog: false
      }
    }
  }
</script>

다음 명령을 사용하여 다른 구성 요소의 메서드를 호출할 수 있음ref.

    <v-card-actions>
      <v-btn
       color="primary"
       dark
       @click="openModal">
      Open Dialog
      </v-btn> <!-- open modal dialog of modal component? -->
      <tenant-number-modal ref="modal"></tenant-number-modal>
    </v-card-actions>
...
<script>
   export default {
      data () {
         return {
            //visible: true,
            //dialog: false,
            //uniqueTenantNumber: ''
         }
      },
      methods: {
         openModal() {
            this.$refs.modal.showModal();
         }
      }
   }
</script>

모달 구성 요소:

<template>
    <v-layout row justify-center>
    ...
        <v-dialog
            v-model="dialog"
            max-width="290">
            <v-card>
                <v-card-title class="headline">test</v-card-title>
            </v-card>
        </v-dialog>
    </v-layout>
</template>

<script>
  export default {
    data () {
      return {
        dialog: false
      }
    },
    methods: {
       showModal() {
       this.dialog = true;
       }
    }
  }
</script>

당신이 할 수 있는 것은 이벤트 버스를 만드는 것이다.이렇게 하면 한 번에 1개 이상의 구성 요소에 메시지를 보낼 수 있다.일단 당신이 메시지를 내보내고 나면, 듣고 있는 모든 구성요소가 실행될 것이다.

먼저 버스를 만들어야 한다.

버스 js

import Vue from 'vue';
export const EventBus = new Vue();

사용자가 호출하는 메시지를 내보낼 구성 요소 다음EventBus.$emit(name, data)

구성요소 A.js

import { EventBus } from './bus.js';

export default {
  methods: {
    emitGlobalClickEvent() {
      EventBus.$emit('i-got-clicked', 'extra data');
    }
  }
}

그렇다면 다른 구성 요소에서는 이벤트에 귀를 기울이면 된다.구성 요소에 다음과 같은 항목을 추가할 수 있으며, 이 경우EventBus.$on(name, handle)또는 한 번만 듣기를 원하는 경우 사용EventBus.$once(name, handle).

성분 B.js

import { EventBus } from './bus.js';

export default {
  created() {
    EventBus.$on('i-got-clicked', data => {
      console.log(data)
      // You can then call your method attached to this component here
      this.openModal()
    });
  },
  methods: {
    openModal() {
      console.log('I am opening')
    }
  }
}

테스트모달.vue:

<template>
  <v-dialog v-model="modalState" max-width="500px">
    <v-card>
      <v-card-title>
        This is a modal in another component.
      </v-card-title>
      <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn color="primary" @click="modalState = false">
          Close
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script>
export default {
  data() {
    return {
      modalState: false,
    }
  },
  methods: {
    showModal() {
      this.modalState = true
    },
  },
}
</script>

상위 파일(index.vue):

<template>
  <v-layout column justify-center align-center>
    <v-flex xs12 sm8 md6>
      <test-modal ref="customModal" />
      <v-btn large color="primary" @click.stop="runModal">
        Run Modal
      </v-btn>
    </v-flex>
  </v-layout>
</template>

<script>
import TestModal from '~/components/TestModal.vue'

export default {
  components: {
    TestModal,
  },
  methods: {
    runModal() {
      this.$refs.customModal.showModal()
    },
  },
}
</script>

다른 구성 요소에서 구성 요소의 모든 메서드를 호출하려면

추가 a$on의 역할을 하다$root탑재된 단면으로부터의 인스턴스그런 다음 에 접근하는 다른 구성요소를 호출하십시오.$root그리고 부름$emit기능을 발휘하다

첫 번째 구성 요소:

    mounted() {
        this.$root.$on('mySpecialName', () => {
            // your code goes here
        }
    }

두 번째 구성 요소:

    someComponent2Method: function(){
     // your code here
     this.$root.$emit('mySpecialName') //like this
    },

참조URL: https://stackoverflow.com/questions/53728386/vue-call-method-of-another-component

반응형