1
votes

I am trying to put a dialog inside an autocomplete component

<v-autocomplete v-model="item.selected_item"
 :items="items"
 item-text="name"
 return-object
 single-line
 @change="setItemId(item)"
>
  <div slot="prepend-item">
      <add-item></add-item>
  </div>
</v-autocomplete>

the code for component <add-item>

<v-dialog persistent v-model="dialog" width="500">
  <template v-slot:activator="{ on, attrs }">
      <v-btn  text block v-bind="attrs" v-on="on">{{__("Add Item")}}</v-btn>
  </template>
  <v-card>
  </v-card>
</v-dialog>

now , the dialog button actually shows up inside the autocomplete , but the problem is that the dialog automatically goes of on any mouse click ,

I noticed that this is related somehow to the autocomplete component , I tried to put the <add-item> component outside of the autocomplete and it worked fine .

how can this be solved ?

1

1 Answers

1
votes

Instead of putting the whole <add-item/> inside the autocomplete, you can separate the button and the dialog itself, then control the dialog whenever the button is clicked. We can base our solution at this example. We will declare a variable dialog that will control our add-item dialog's visibility. That variable will be handled by our button inside the autocomplete.

Main Component:

<v-autocomplete
...
>
  <div slot="prepend-item">
     <v-btn text block @click="dialog = true">{{"Add Item"}}</v-btn>
  </div>
</v-autocomplete>

<add-item v-model="dialog"/>    <!-- Pass the dialog variable to the add-item component -->
export default {
  data: () => ({
    items: [...],
    dialog: false     // let's close the dialog initially.
  })
}

Add Item Component:

<v-dialog persistent :value="value" width="500">
  <v-card>
    ...
    <!-- To close the dialog, we'll need to use $emit() to
         let our parent know that the value had changed.  -->
    <v-btn @click="$emit('input', false)">Close Dialog</v-btn>  
  </v-card>
</v-dialog>
export default {
  props: ["value"],   // Pass the value of the dialog from the main component
};

Notice that we used $emit() when we want to close our dialog. We need to use that because the variable that is controlling the dialog is from the main component, and the best way to change the value from add-item is by emitting a value. More explanation here.

enter image description here

Here is a demo.