If you look at their autocomplete component: https://mui.com/material-ui/react-autocomplete/
After you click a suggestion in the dropdown, the input box keeps focus... How do they do that? In every variation of this in my own vue app (not using material UI) I can't get the click event to stop an input from losing focus.
I have tried googling this for quite some time and there is no clear solution that I see. For example, people suggest mousedown/touchstart but that would break scrolling (via dragging the dropdown). MaterialUI obviously doesn't have this problem, and doesn't seem to be using mousedown.
I've tried analyzing the events using Chrome dev tools and I can only see a single click event, but with minified code it's difficult to tell what's going on.
Vuetify also does this: https://github.com/vuetifyjs/vuetify/blob/master/packages/vuetify/src/components/VAutocomplete/VAutocomplete.ts
I did find this too which is helpful, if anyone comes across this issue https://codepen.io/Pineapple/pen/MWBVqGW
Edit Here's what Im doing:
<app-input-autocomplete
#autocomplete-select="onSelect"
#autocomplete-close="onClose"
:open="open">
<template #default="{ result }">
<div class="input-autocomplete-address">
{{ result.address }}
</div>
</template>
</app-input-autocomplete>
and then in app-input-autocomplete:
<template>
<app-input
#focus="onFocus"
#blur="onBlur"
v-bind="$attrs">
<template #underInput>
<div ref="dropdown" v-show="open" class="input-autocomplete-dropdown">
<div class="input-autocomplete-results">
<div v-for="result in results" :key="result.id" #click="onClick(result)" class="input-autocomplete-result">
<slot :result="result" />
</div>
</div>
</div>
</template>
</app-input>
</template>
<script>
import { ref, toRef } from 'vue';
import AppInput from '#/components/AppInput.vue';
import { onClickOutside } from '#vueuse/core';
export default {
components: {
AppInput,
},
inheritAttrs: false,
props: {
open: {
type: Boolean,
default: false,
},
results: {
type: Array,
default: () => ([]),
},
},
emits: ['autocomplete-close', 'autocomplete-select'],
setup(props, { emit }) {
const dropdown = ref(null);
const open = toRef(props, 'open');
const focused = ref(false);
onClickOutside(dropdown, () => {
if (!focused.value && open.value) {
emit('autocomplete-close');
}
});
return {
dropdown,
focused,
};
},
methods: {
onFocus() {
this.focused = true;
},
onBlur() {
this.focused = false;
},
onClick(result) {
this.$emit('autocomplete-select', result);
},
},
};
</script>
I solved this by doing the following, thanks to #Claies for the idea to look, and also this link:
https://codepen.io/Pineapple/pen/MWBVqGW
event.preventDefault on mousedown
#click on result behaves like normal (close input)
#click/#focus on input set open = true
#blur sets open = false
Related
EDIT: Here's a repo I made for easier parsing.
I have a Component that lists products in a datatable. The first column of the table is a link that shows a modal with a form of the product that was clicked (using its ID). I'm using the PrimeVue library for styling and components.
<template>
<Column field="id" headerStyle="width: 5%">
<template #body="slotProps">
<ProductForm :product="slotProps.data" :show="showModal(slotProps.data.id)" />
<a href="#" #click.stop="toggleModal(slotProps.data.id)">
<span class="pi pi-external-link"> </span>
</a>
</template>
</Column>
</template>
<script>
import ProductForm from "./forms/ProductForm";
export default {
data() {
return {
activeModal: 0,
}
},
components: { ProductForm },
methods: {
toggleModal: function (id) {
if (this.activeModal !== 0) {
this.activeModal = 0;
return false;
}
this.activeModal = id;
},
showModal: function (id) {
return this.activeModal === id;
},
},
</script>
The modal is actually a sub component of the ProductForm component (I made a template of the Modal so I could reuse it). So it's 3 components all together (ProductList -> ProductForm -> BaseModal). Here's the product form:
<template>
<div>
<BaseModal :show="show" :header="product.name">
<span class="p-float-label">
<InputText id="name" type="text" :value="product.name" />
<label for="name">Product</label>
</span>
</BaseModal>
</div>
</template>
<script>
import BaseModal from "../_modals/BaseModal";
export default {
props: ["product", "show"],
components: { BaseModal },
data() {
return {};
},
};
</script>
When the modal pops up it uses the ProductForm subcomponent. Here is the BaseModal component:
<template>
<div>
<Dialog :header="header" :visible.sync="show" :modal="true" :closable="true" #hide="doit">
<slot />
</Dialog>
</div>
</template>
<script>
export default {
props: {
show: Boolean,
header: String,
},
methods: {
doit: function () {
let currentShow = this.show;
this.$emit("showModel", currentShow)
},
},
data() {
return {
};
},
};
</script>
I'm passing the product object, and a show boolean that designates if the modal is visible or not from the first component (ProductList) all the way down through the ProductForm component and finally to the BaseModal component. The modal is a PrimeVue component called Dialog. The component actually has it's own property called "closable" which closes the modal with an X button when clicked, that is tied to an event called hide. Everything actually works. I can open the modal and close it. For some reason I have to click the another modal link twice before it opens after the initial.
The issue is when I close a modal, I get the Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "show" error. I've tried everything to emit to the event and change the original props value there, but the error persists (even from the code above) but I'm not sure if because I'm 3 components deep it won't work. I'm pretty new to using props and slots and $emit so I know I'm doing something wrong. I'm also new to laying out components this deep so I might not even be doing the entire layout correctly. What am I missing?
Well you are emitting the showModel event from BaseModal but you are not listening for it on the parent and forwarding it+listening on grandparent (ProductForm)
But the main problem is :visible.sync="show" in BaseModal. It is same as if you do :visible="show" #update:visible="show = $event" (docs). So when the Dialog is closed, PrimeVue emits update:visible event which is picked by BaseModal component (thanks to the .sync modifier) and causes the mutation of the show prop inside BaseModal and the error message...
Remember to never use prop value directly with v-model or .sync
To fix it, use the prop indirectly via a computed with the setter:
BaseModal
<template>
<div>
<Dialog :header="header" :visible.sync="computedVisible" :modal="true" :closable="true">
<slot />
</Dialog>
</div>
</template>
<script>
export default {
props: {
show: Boolean,
header: String,
},
computed: {
computedVisible: {
get() { return this.show },
set(value) { this.$emit('update:show', value) }
}
},
};
</script>
Now you can add same computed into your ProductForm component and change the template to <BaseModal :show.sync="computedVisible" :header="product.name"> (so when the ProductForm receives the update:show event, it will emit same event to it's parent - this is required as Vue event do not "bubble up" as for example DOM events, only immediate parent component receives the event)
Final step is to handle update:show in the ProductList:
<ProductForm :product="slotProps.data" :show="showModal(slotProps.data.id)" #update:show="toggleModal(slotProps.data.id)"/>
I'm using vuetify, and I have a tooltip over a button.
I doesn't want to show the tooltip on hover nor on click, I want to show the tooltip if some event is triggered.
translate.vue
<v-tooltip v-model="item.showTooltip" top>
<template v-slot:activator="{}">
<v-btn #click="translateItem(item)"> Call API to translate</v-btn>
</template>
<span>API quota limit has been reached</span>
</v-tooltip>
<script>
export default(){
props: {
item: { default: Objet}
}
methods: {
translateItem: function (item) {
axios
.post(baseURL + "/translateAPI", {
text: item.originTrad;
})
.then((res) => {
if (apiQuotaLimitReached(res) {
// If limit is reached I want to show the tooltip for some time
item.showTooltip = true;
setTimeout(() => {item.showTooltip = false;}, 3000);
} else { ..... }}}
</script>
itemSelect.vue (where I create object item and then use router push to transmit it to the translation page)
<script>
export default(){
methods: {
createItem: function () {
item.originTrad = "the text to translate"
....
item.showTooltip = false;
this.$router.push({
name: "translate",
params: {
"item": item,
},
}); }}
</script>
As you can see I removed the v-slot:activator="{ on }" and v-on="on" that I found on the exemple:https://vuetifyjs.com/fr-FR/components/tooltips/ , because I don't want to show the tooltip on hover. But It doesn't work as expected, the tooltip is not showing properly.
Some help would be great :)
For starters, you are trying to change a prop in the child component, something that you should not do:
[Vue warn]: Avoid mutating a prop directly since the value will be
overwritten whenever the parent component re-renders. Instead, use a
data or computed property based on the prop's value. Prop being
mutated: "item.showTooltip"
So start by making a separate data variable for showTooltip (doesn't need to be a property of item perse) and try setting it to true to see what happens (and of course change v-model="item.showTooltip" to v-model="showTooltip" on v-tooltip)
I have a v-dialog that I use to pop up a date picker when needed. To show it, I bind a value with v-modle. I use the click:outside events to trigger to function that is supposed to close it once it's clicked outside so I can trigger it again (if I click outside, the dialog is dismissed, but the value stays 'true', so I can't show it more than once). There must be something I'm doing wrong.
Here's my dialog :
<template>
<v-dialog
v-model="value"
#click:outside="closeDialog"
>
<v-date-picker
v-model="date"
/>
<v-divider/>
<div>fermer</div>
</v-dialog>
</template>
<script>
export default {
name: 'DatePickerDialog',
props: ['value'],
data() {
return {
colors,
date: null,
}
},
methods: {
closeDialog() {
this.value = false;
}
}
}
</script>
And what calls it is as simple as this :
<template>
<div>
<v-btn #click="inflateDatePicker">inflate date picker</v-btn>
<date-picker-dialog v-model="showDatePicker"/>
</div>
</template>
<script>
import DatePickerDialog from '../../../../views/components/DatePickerDialog';
export default{
name: "SimpleTest",
components: {
DatePickerDialog
},
data() {
return {
showDatePicker: false,
};
},
methods:{
inflateDatePicker() {
this.showDatePicker = true;
},
},
}
</script>
So I can inflate it with no problem. Then though I'm not able to go inside closeDialog() (verified by debugging and trying to log stuff). So what is happening that makes it so I'm not able to enter the function? Documentation doesn't specify if you need to use it differently from regular #click events
The problem was in my closeDialog function. this.value = false did not notify the parent component of the value change. So I had to change it to this in order for it to work properly :
closeDialog() {
this.$emit('input', false);
},
With this is works perfectly fine.
I'm building a small vue application where among other things it is possible to delete an entry of a music collection. So at this point I have a list of music albums and next to the entry I have a "delete" button. When I do the following:
<li v-for="cd in cds">
<span>{{cd.artist}} - {{cd.album}}</span> <button v-on:click="deleteAlbum(cd.ID)">Delete</button>
</li>
and then in my methods do:
deleteAlbum(id){
this.$http.delete('/api/cds/delete/'+id)
.then(function(response){
this.fetchAll()
// });
},
this works fine so far, but to make it more nice, I want the delete functionality to appear in a modal/popup, so I made the following changes:
<li v-for="cd in cds">
<div class="cd-wrap">
<span>{{cd.artist}} - {{cd.album}}</span>
<button #click="showDeleteModal({id: cd.ID, artist: cd.artist, album: cd.album})" class="btn">Delete</button>
</div>
<delete-modal v-if="showDelete" #close="showDelete = false" #showDeleteModal="cd.ID = $event"></delete-modal>
</li>
so, as seen above I created a <delete-modal>-component. When I click on the delete button I want to pass the data from the entry to <delete-modal> component with the help of an eventbus. For that, inside my methods I did this:
showDeleteModal(item) {
this.showDelete = true
eventBus.$emit('showDeleteModal', {item: item})
}
Then, in the <delete-modal>, inside the created()-lifecycle I did this:
created(){
eventBus.$on('showDeleteModal', (item) => {
console.log('bus data: ', item)
})
}
this gives me plenty of empty opened popups/modals!!??
Can someone tell me what I'm doing wrong here?
** EDIT **
After a good suggestion I dumped the eventBus method and pass the data as props to the <delete-modal> so now it looks like this:
<delete-modal :id="cd.ID" :artist="cd.artist" :album="cd.album"></delete-modal>
and the delete-modal component:
export default {
props: ['id', 'artist', 'album'],
data() {
return {
isOpen: false
}
},
created(){
this.isOpen = true
}
}
Only issue I have now, is that it tries to open a modal for each entry, how can I detect the correct ID/entry?
I am going to show you how to do it with props since it is a parent-child relation.I will show you a simple way of doing it.You need to modify or add some code of course in order to work in your app.
Parent component
<template>
<div>
<li v-for="cd in cds" :key="cd.ID">
<div class="cd-wrap">
<span>{{cd.artist}} - {{cd.album}}</span>
<button
#click="showDeleteModal({id: cd.ID, artist: cd.artist, album: cd.album})"
class="btn"
>
Delete
</button>
</div>
<delete-modal v-if="showDelete" :modal.sync="showDelte" :passedObject="objectToPass"></delete-modal>
</li>
</div>
</template>
<script>
import Child from 'Child'
export default {
components: {
'delete-modal': Child
},
data() {
return {
showDelete: false,
objectToPass: null,
//here put your other properties
}
},
methods: {
showDeleteModal(item) {
this.showDelete = true
this.objectToPass = item
}
}
}
</script>
Child Component
<template>
/* Here put your logic component */
</template>
<script>
export default {
props: {
modal:{
default:false
},
passedObject: {
type: Object
}
},
methods: {
closeModal() { //the method to close the modal
this.$emit('update:modal')
}
}
//here put your other vue.js code
}
</script>
When you use the .sync modifier to pass a prop in child component then,there (in child cmp) you have to emit an event like:
this.$emit('update:modal')
And with that the modal will close and open.Also using props we have passed to child component the object that contains the id and other stuff.
If you want to learn more about props, click here
I am using a dropdown menu components in vuejs to make normal dropdown menu.
My code is for dropdown component is :
<template>
<span class="dropdown" :class="{shown: state}">
toggle menu
<div class="dropdown-menu" v-show="state">
<ul class="list-unstyled">
<slot></slot>
</ul>
</div>
</transition>
</span>
</template>
<script>
export default {
name: 'dropdown',
data () {
return {
state: false
}
},
methods: {
toggleDropdown (e) {
this.state = !this.state;
}
}
}
</script>
Now I am importing the dropdown component in my VUE app at various place by using following code in the template
<dropdown>
<li>
Action
</li>
</dropdown>
Now that is working fine but I want that only one dropdown should be active at the same time.
I have done little research and found that i can use plugins like https://github.com/davidnotplay/vue-my-dropdown but I don't want to use that. Again i have also studied how the above example works but I want to implement this dropdown functionality in such a way that my dropdown component would take care of all event related to dropdown. So can you help me how to achieve that?
I know it's quite an old question but I think the best way to do that without any external plugins is to add a click listener to mounted lifecycle hook (and remove it on beforeDestroy hook) and filter the clicks on your component so it only hides when clicked outside.
<template>
<span class="dropdown" :class="{shown: state}">
toggle menu
<div class="dropdown-menu" v-show="state">
<ul class="list-unstyled">
<slot></slot>
</ul>
</div>
<transition/>
</span>
</template>
<script>
export default {
name: 'dropdown',
data () {
return {
state: false
}
},
methods: {
toggleDropdown (e) {
this.state = !this.state
},
close (e) {
if (!this.$el.contains(e.target)) {
this.state = false
}
}
},
mounted () {
document.addEventListener('click', this.close)
},
beforeDestroy () {
document.removeEventListener('click',this.close)
}
}
</script>
Have a look at vue-clickaway.(Link)
Sometimes you need to detect clicks outside of the element (to close a modal window or hide a dropdown select). There is no native event for that, and Vue.js does not cover you either. This is why vue-clickaway exists. Please check out the demo before reading further.
In Vue 3 the following should work
Note that the #click.stop on the dropdown trigger and on the dropdown content prevents the document event from executing the close function.
<template>
<div class="dropdown" :class="{'is-active': dropdown.active.value}">
<div class="dropdown-trigger">
<button class="button" #click.stop="dropdown.active.value = !dropdown.active.value">
Toggle
</button>
</div>
<div class="dropdown-menu" role="filter">
<div class="dropdown-content" #click.stop>
<!-- dropdown items -->
</div>
</div>
</div>
</template>
<script>
import { defineComponent, ref, onMounted, onBeforeUnmount } from "vue";
export default defineComponent({
name: "Dropdown",
setup(){
const dropdown = {
active: ref(false),
close: () => {
dropdown.active.value = false
}
}
onBeforeUnmount(() => {
document.removeEventListener('click', dropdown.close)
})
onMounted(() => {
document.addEventListener('click', dropdown.close)
})
return {
dropdown
}
}
})
</script>
This example uses bulma but off course you don't need to.
You can make use of the blur event, e.g. if you add a method:
close() {
setTimeout(() => {
this.state = false;
}, 200);
}
And set the blur event for your link:
toggle menu
Then the dropdown will get hidden whenever your toggle link loses focus.
The setTimeout is necessary because Javascript click events occur after blur, which would result in your dropdown links being not clickable. To work around this issue, delay the menu hiding a little bit.