Vue components Event Handling - vue.js

I have a component button where I use that button almost everywhere in my site.
Its an SVG button with some animation on hover. The button works fine.
<template>
<a class="button"
#mouseover="buttonEnter"
#mouseout="buttonLeave">
<svg viewBox="0 0 180 60">
<path ref="btnPath" d="..." />
</svg>
<span ref="btnSpan">
<slot>Button slot</slot>
</span>
</a>
</template>
<script>
import { buttonEnter, buttonleave } from '../assets/animate'
export default {
name: 'AnimButton',
methods: {
buttonEnter(event) {
buttonEnter(this.$refs.btnPath, this.$refs.btnSpan)
},
buttonLeave(event) {
const buttonSpan = event.currentTarget.querySelector('span')
buttonleave(this.$refs.btnPath, this.$refs.btnSpan)
},
},
}
</script>
Now I wanna use this button as a submit button in my form.The hover events are happening, but seems the #click event is not triggering.
Probably i'm missing something bad.
<form>
<input type="email">
<input type="subject">
<input type="message">
<anim-button type="submit" #click="submit">
Submit
</anim-button>
</form>
<script>
import AnimButton from '~/components/AnimButton.vue'
export default {
components: {
AnimButton,
},
methods: {
submit: function() {
console.log('submit')
},
}
</script>

You can both use #click.native like suggested in comment (see here) or put #click in your AnimButton, $emit some event and catch this event in parent component.

Related

Popup on top of each other VUEJS3

I want to put several Buttons, each one opening a different Popup. A Popup would print data concerning its Button.
I have a Popup.vue component :
<template>
<div class="popup">
<div class="popup-inner">
<slot />
<Button class="popup-close" #click="TogglePopup()">
Close
</Button>
</div>
</div>
</template>
<script>
export default {
props: ['TogglePopup']
}
</script>
And in another .vue I call it like that :
<template>
<div v-for="infoItem in data" :key="infoItem.name"> // loop to create several buttons
<Button
icon="pi pi-eye"
#click="() => TogglePopup('buttonTriggerDetail')">
</Button>
<Popup
v-if="popupTriggers.buttonTriggerDetail"
:TogglePopup="() => TogglePopup('buttonTriggerDetail')"
>
{{ infoItem.control }}
</Popup>
</div>
</template>
<script>
import ...
export default {
computed: {
data() {
return this.$store.state.data;
},
},
mounted() {
this.$store.dispatch("getData");
},
setup() {
const popupTriggers = ref({
buttonTriggerDetail: false
});
const TogglePopup = (trigger) => {
popupTriggers.value[trigger] = !popupTriggers.value[trigger];
};
return {
Popup,
TogglePopup,
popupTriggers,
};
},
};
</script>
So it prints several Button but when I click on one, it don't open the Popup with the data of this Button, it always prints the data of the last Button. I think in reality it places all the pop up on top of each others.
How can I do to open only the good Popup with the good data ?
Thanks
The mistake is that you are rendering 3 popups when you need only one with certain props. Think of your popups as of tabs: let popup be rendered by clicking on certain button and pass in props you need, for example:
<template>
<div v-for="infoItem in data" :key="infoItem.name"> // loop to create several buttons
<Button
icon="pi pi-eye"
#click="clickHandler">
</Button>
</div>
<Popup
v-if="popupTriggered"
:TogglePopup="() => TogglePopup('buttonTriggerDetail')"
>
{{ data[currentActiveItem].control }}
</Popup>
</template>
<script>
import ...
export default {
data () {
currentActiveItem: 0,
popupTriggered: false
},
methods: {
clickHandler (index) {
this.popupTriggered = true
this.currentActiveItem = index
}
}
... // other component data
};
</script>
I wrote my example in Vue 2 style because I haven't worked with Composition API yet but I hope you got the idea.

Vue open a component in a component

In App.vue I have a button to open a component . Inside the component BigForm, I also have a button to open a component named, . But as I open the component. Vue re-render the page with the warning:
The "data" option should be a function that returns a per-instance value in component definitions.
App.Vue
<template>
<div id="app">
<button #click="showModal()">Show</button>
<BigForm v-if="modal" />
</div>
</template>
<script>
import BigForm from "./components/BigForm";
export default {
name: "App",
components: {
BigForm,
},
data() {
return {
modal: false,
};
},
methods: {
showModal() {
this.modal = !this.modal;
},
},
};
</script>
BigForm.vue:
<template>
<div class="hello">
<form style="height: 300px; width: 300px; background-color: green">
<button #click="showSmallForm()">Show small form</button>
<SmallForm
v-if="toggleSmallForm"
style="width: 100px; height: 100px; background-color: yellow"
/>
</form>
</div>
</template>
<script>
import SmallForm from "./SmallForm";
export default {
name: "HelloWorld",
components: {
SmallForm,
},
data() {
return {
toggleSmallForm: false,
};
},
methods: {
showSmallForm() {
this.toggleSmallForm = !this.toggleSmallForm;
},
},
};
</script>
And SmallForm.vue:
<template>
<form>
<input placeholder="Small form input" />
<button>This is small form</button>
</form>
</template>
This is the code to my example in codesandbox:
https://codesandbox.io/s/late-cdn-ssu7f?file=/src/App.vue
The problem is not related to Vue itself but the HTML.
When you use <button> inside <form>, the default type of the button is submit (check this) - when you click the button, the form is submitted to the server causing the page to reload.
You can prevent that by explicitly setting type <button type="button"> (HTML way) or by preventing default action (Vue way) <button #click.prevent="showSmallForm()">Show small form</button> (see event modifiers)
Also note that using <form> in another <form> is not allowed in HTML

How can I emit from component and listen from another one?

I have in Layout.vue to components one TheSidebar second TheHeader, there is a button in TheHeader to open the sidebar in TheSidebarcomponent.
I need to when I click the button in header open the sidebar:
My try:
in TheHeader:
methods: {
openSidebar() {
this.$root.$emit("open-sidebar");
},
},
in TheSidebar
data() {
return {
sidebarOpen: false,
};
},
mounted() {
this.$root.$on("open-sidebar", (this.sidebarOpen = true));
},
I'm using VUE 3 so I got this error in console: TypeError: this.$root.$on is not a function so How can communicate ?
you can use something like tiny emitter it works fine and doesn't care about parent child relationship
var emitter = require('tiny-emitter/instance');
emitter.on('open-sidebar', ({isOpen}) => {
//
});
emitter.emit('open-sidebar', {isOpen : true} );
You can only pass props to a direct child component, and
you can only emit an event to a direct parent. But
you can provide and eject from anywhere to anywhere
Per another answer, provide and eject may be your best bet in Vue 3, but I created a simple example of how to implement with props/events. Built with Vue 2 as I haven't worked with 3 yet, but should be usable in Vue 3 as well.
Parent.vue
<template>
<div class="parent">
<div class="row">
<div class="col-md-6">
<h4>Parent</h4>
<hr>
<child-one #show-child-two-event="handleShowChildTwoEvent" />
<hr>
<child-two v-if="showChildTwo" />
</div>
</div>
</div>
</template>
<script>
import ChildOne from './ChildOne.vue'
import ChildTwo from './ChildTwo.vue'
export default {
components: {
ChildOne,
ChildTwo
},
data() {
return {
showChildTwo: false
}
},
methods: {
handleShowChildTwoEvent() {
this.showChildTwo = true;
}
}
}
</script>
ChildOne.vue
<template>
<div class="child-one">
<h4>Child One</h4>
<button class="btn btn-secondary" #click="showChildTwo">Show Child Two</button>
</div>
</template>
<script>
export default {
methods: {
showChildTwo() {
this.$emit('show-child-two-event');
}
}
}
</script>
ChildTwo.vue
<template>
<div class="child-two">
<h4>Child Two</h4>
</div>
</template>

custom v-focus not work when there are many v-if in parent node

I define the custom directive "focus" in my component:
<script>
export default {
name: 'demo',
data () {
return {
show: true
}
},
methods: {
showInput () {
this.show = false
}
},
directives: {
focus: {
inserted: function (el) {
el.focus()
}
}
}
}
And this is my html template:
<template>
<div>
<input type="number" id="readonly" v-if="show">
<button type="button" #click="showInput" v-if="show">show</button>
<input type="number" id="timing" v-model="timing" v-if="!show" v-focus>
</div>
</template>
But when I click the button, input#timing can't autofocus.
When I put input#readonly and button into a div and use only one v-if, input#timing can be autofocus:
<template>
<div>
<div v-if="show">
<input type="number" id="readonly">
<button type="button" #click="showInput">show</button>
</div>
<input type="number" id="timing" v-model="timing" v-if="!show" v-focus>
</div>
</template>
This is why???
The directive's code is indeed running and focusing the <input>.
But it is being removed from the DOM! When this happens, it loses focus. Check the console of the fiddle below: https://jsfiddle.net/acdcjunior/srfse9oe/21/
Another important point is that, when inserted is called, the <input id="timing"> is in the DOM (as mentioned above), but it is in the DOM at the wrong location (between <p>a</p> and <p>b</p> where it was never supposed to be). This happens because Vue tries to reuse elements.
And when the nextTick triggers (see fiddle), it is in its correct placement (between <p>c</p> and <p>d</p>), because Vue moved it to the correct location. And is this moving that is taking focus out.
And because nextTick runs after the DOM moving around is done, the focus persists (see below).
Using Vue.nextTick():
Defer the callback to be executed after the next DOM update cycle. Use
it immediately after you’ve changed some data to wait for the DOM
update.
new Vue({
el: '#app',
data() {
return {
show: true,
timing: 123
}
},
methods: {
showInput() {
this.show = false
}
},
directives: {
focus: {
inserted: function(el) {
Vue.nextTick(() => el.focus()); // <======== changed this line
}
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<div>
<input type="number" id="readonly" v-if="show">
<button type="button" #click="showInput" v-if="show">show</button>
<input type="number" id="timing" v-model="timing" v-if="!show" v-focus>
</div>
</div>

VueJS - Swap component on click

In my application I have many buttons. When I press it the button I would like to load a template (that replaces the selected button):
Templates:
Vue.component('component-1', {...});
Vue.component('component-2', {...});
Buttons:
<div id="toReplace">
<button>Button1</button>
<button>Button2</button>
</div>
In this case, when I press Button1 the content of the div toReplace should be component-1.
Sure, each component should have a "close" button that will show the buttons again (in short, the div toReplace) on press.
You need to bind a variable to :is property. And change this variable on button click. Also you will need to combine it with some v-show condition. Like so:
<div id="toReplace">
<div :is="currentComponent"></div>
<div v-show="!currentComponent" v-for="component in componentsArray">
<button #click="swapComponent(component)">{{component}}</button>
</div>
</div>
<button #click="swapComponent(null)">Close</button>
new Vue({
el: 'body',
data: {
currentComponent: null,
componentsArray: ['foo', 'bar']
},
components: {
'foo': {
template: '<h1>Foo component</h1>'
},
'bar': {
template: '<h1>Bar component</h1>'
}
},
methods: {
swapComponent: function(component)
{
this.currentComponent = component;
}
}
});
Here is quick example:
http://jsbin.com/miwuduliyu/edit?html,js,console,output
You can use v-bind:is="CurrentComponent" and #click=ChangeComponent('SecondComponent'). The argument has to be a string. To use the <component/> make sure your ExampleComponent has a slot
<Template>
<div>
<ExampleComponent>
<component v-bind:is = "CurrentComponent"/>
</ExampleCompoent>
<button #click="ChangeComponent('SecondComponent')">
</button>
</div>
</template>
<script>
import ExampleComponent from '#/components/ExampleComponent.vue'
import SecondComponent from '#/components/SecontComponent.vue'
export default{
...
data(){
return{
CurrentComponet:null
}
}
methods:{
ChangeComponent(NewComponent){
this.CurrentComponent = NewComponent
}