首页 > 解决方案 > 另一个组件的vue调用方法

问题描述

我有两个组件,一个 Card 组件和一个模态组件,模态组件包含模态元素,在我的 Card 组件中,我想有一个按钮来打开我的模态组件的模态窗口。我该如何管理,到目前为止我已经这样做了:

我的卡片组件:

<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>

标签: javascriptvue.jsvuejs2

解决方案


您可以使用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>

推荐阅读