GaryO
GaryO

Reputation: 6338

How to run API calls in Vuetify dialog only when the dialog is shown?

I have a dialog in Vuetify that needs some API calls to fill in the view. I'd like to not run those heavyweight API calls when the main screen loads (onMounted), but only when the dialog is first shown (and ideally shut down my API listener when the dialog is closed). But I can't find any way to do that. I looked at v-intersect but it looks complicated and error-prone, and not available on IE. Is there any event fired by Vue or Vuetify, or a reactive value set, when a dialog is shown?

I'm using Vue 2 with the composition-api, if that's helpful.

Here's a short version of the RenderDialog component (just the script part):

export default defineComponent({
  name: 'RenderDialog',
  setup(props, context) {
    const state = reactive({
      dialogValue: 0,
      expensiveComputationResult: 0,
    })

    watchEffect(async () => {
      state.expensiveComputationResult = await doExpensiveComputation(state.dialogValue)
    })

    return {state}
  }
})

and here's how it's called from the parent:

          <render-dialog>
            <template v-slot:activator="{ on }">
              <v-btn v-on="on">Open Dialog</v-btn>
            </template>
          </render-dialog>

Right now, it calls doExpensiveComputation every time the page loads. I want to defer that until the user opens the dialog.

Upvotes: 0

Views: 943

Answers (1)

MarSoft
MarSoft

Reputation: 3913

Here's what I did in a similar situation — a small explanation of AndrewShmig's comment:

<template>
  ...
  <v-dialog v-model="dialogVisible">
    ...
  </v-dialog>
</template>

<script>
  export default {
    ...
    data() {
      return {
        ...
        dialogVisible: false,
        requiredData: null, // expensive to load
      }
    },
    watch: {
      dialogVisible(newVal, oldVal) {
        if(newVal && this.requiredData === null) {
          this.doLoadTheData()
        }
      },
    },
    ...
  }
</script>

Upvotes: 1

Related Questions