-
-
Notifications
You must be signed in to change notification settings - Fork 33.7k
Is it possible to emit event from component inside slot #4332
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
You cannot listen to events on It seems you are trying to make a slot container communicate with a slot child - in most cases this means the two components are coupled by-design, so you can do something like I am still open to ideas on improving the ways slot parent and child can communicate, but events on |
not trying to wake this up from the dead but...
the child's code looks something like:
the usage is something like this:
in order for the slot child to fulfill the parent's interface, they should emit an event to turn the spinner to inactive. One can argue that using $parent.emit with $on (per suggestion @yyx990803 above) complicates the issue as you need to take into consideration the life cycle of components into this. if, for example: long story short, in order to get the full slot power I do believe some sort of a mechanism should be introduced. |
In your case: <vue-loading-wrapper>
<vue-child></vue-child>
</vue-loading-wrapper> The state of <vue-loading-wrapper :loading="childLoading">
<vue-child @load="childLoading = false"></vue-child>
</vue-loading-wrapper> |
I'm having a lot of trouble with this. I can see that this will be a high use case, or at least I thought it would be. Personally I have a card ui that carries a background, inside the card can be any content so it uses
According to the documentation this should work and it would do if I could pass JSON over and make the HTML above into a component using In this case Edit:
It's very hacky and not "very Vue" at all... Wish there was a way to bubble up an event inside a slot... |
Holy shit @TomS- , such mixing php and Vue should be punishable by death! Your code is horribly unmaintainable. |
@Danonk I hardly think "punishable by death" is fair. Not that I have to justify myself to you, I'm using a PHP CMS that doesn't have a REST API and I want to use Vue. Luckily you don't have to deal with the code I'm writing. |
I'm facing with problem with too Currently I am creating a Modal in which will contain any Form components My modal contain tag
I call Modal component like below and I place LoginForm component inside Modal component
Inside the LoginForm component, I place an anchor tag to close the modal
However, this button is not working. Whenever I click the button, I get this error:
Now I'm stuck at this. I have already tried the suggestion from @Justineo but cannot make it work, any idea? |
Hi! I arrived at the exact same problem that @dodatrmit3618835, and I think that in cases like this, listening to events on slot could be a good solution. |
👍 I could also use this, my use case is trying to use one or more date picker components within a data table component. I'd like the date picker to be able to emit an event with their key/value pair for the data table to update itself with.
Then these date pickers get slotted into their appropriate places in the data table component. If the slot can render anything why restrict event listeners? |
@dodatrmit3618835 I had exactly the same problem, scoped slots can you help in this case: Modal (parent) has to get a scoped slot with a closeHandler property, this should be some kind of method to close your modal, please adapt to your needs - my usecase uses uiv for a bootstrap modal: <template>
<div>
<Btn
type="primary"
block
@click="open=true">{{ buttonText }}</Btn>
<Modal
v-model="open"
:title="title">
<slot
v-if="open"
:closeHandler="closeHandler"/>
</Modal>
</div>
</template>
<script>
import { Modal, Btn } from 'uiv'
export default {
name: 'ModalButton',
components: {
Modal,
Btn
},
props: {
buttonText: String,
title: String
},
data () {
return {
open: false
}
},
methods: {
closeHandler: function () {
this.open = false
}
}
}
</script> Your form (or whatever inner container) has to dispatch an event you can handle from the outside (close event in your case, mine is called productSelected) - use the component as following now: <ModalButton button-text="My fancy button">
<template slot-scope="{closeHandler}">
<ProductList @productSelected="closeHandler"/>
</template>
</ModalButton> This will allow you to wire up the parent/child components without any unneeded coupling. |
This is my solution (similar to @aggrosoft 's): <!-- Will be top level after the containing <div> -->
<grand-parent>
<slot slot="parent"></slot>
</grand-parent>
<!-- Should be in a <grand-parent> -->
<parent>
<!-- 1. Actually owns patChild method, does some magic but needs to know from a slot/child -->
<!-- patChild (...receives data) { ...Magical!!! } -->
<!-- 5. Receives the even through method call. -->
<slot name="child" :patChild="pathChild">
Expects a child
</slot>
</parent>
<!-- Should be in a <parent> -->
<child @click="handleClick">
<!-- 2. Takes the method that needs data through props -->
Accepts patChild as a prop (function)
<!-- 3. Event actually happens here (a slot) -->
<!-- 4. handleClick () { ...some magic; this.patChild(...some data)} -->
</child>
<!-- Composed structure -->
<div>
<grand-parent>
<parent slot="parent">
<child slot="child" slot-scope="{pathChild}" :pathChild="pathChild"></child>
</parent>
</grand-parent>
</div>
|
It's really amazing that many solutions have been given by many developers I wanna give my solution, too Like what I mentioned above, I have several components to handle the Modal which listed below Modal component: Modal.vue Inside Navbar component, I called Modal with "closeModal" methods and Login component
Inside the Modal component, I have
Inside the Login component, there is a Button which contains the click method to trigger the
It can be summarized like this: Modal component listen to And this works like a charm For the solution of @aggrosoft , I have not used the |
@TomS- I also found myself in a similar situation some years ago with a different framework. I suggest you export the data that you need as JSON inside a script tag: <script>
window.someGlobalVariable = <?php json_encode($somedata); ?>
</script>
<script src="/dist/my-nice-vue-dist.js"></script> |
Where would |
Hey @jaiko86 one way is to register this event when parent component is mounted, like:
|
you can use named slots and do something like: |
Is this hacky way of doing this a really bad idea ? |
Pe miercuri, 31 iulie 2019, 10:51:18 EEST, Kemal Tatar <[email protected]> a scris:
<slot name="form"
:saveHandler="values => handleSave(values)"
:cancelHandler="handleCancel"
/>
<template v-slot:form="{saveHandler, cancelHandler}">
<ExampleForm @save="saveHandler" @cancel="cancelHandler" />
</template>
Is this hacky way of doing this a really bad idea ?
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub, or mute the thread.
|
Here's a solution that I use for triggering a method which involves changing the value of a watched prop: OuterComponent: <template>
<slot />
</template> <script>
export default {
props: {
doSomethingTrigger: {
type: Boolean,
default: false,
},
},
watch: {
// we watch the boolean prop and trigger our method when it changes
doSomethingTrigger(oldVal, newVal) {
oldVal !== newVal && this.doSomething();
},
},
methods: {
doSomething() {
// this is what you want to trigger from your slot
}
},
}
</script> InnerComponent: <template>
<OuterComponent :do-something-trigger="doSomethingTrigger">
<button @click="doSomething" />
</OuterComponent>
</template> <script>
export default {
data() {
return {
doSomethingTrigger: false,
};
},
methods: {
doSomething() {
// we change the value of the boolean which is passed
// to our OuterComponent
this.doSomethingTrigger = !this.doSomethingTrigger;
},
},
}
</script> |
Just another solution similar to @aggrosoft and @limistah: Basically, you can adopt an approach I encountered in the Vuetify framework for the v-tooltip component: Code looks like this: <v-tooltip bottom>
<template v-slot:activator="{ on }">
<v-btn color="primary" dark v-on="on">Button</v-btn>
</template>
<span>Tooltip</span>
</v-tooltip> As you can see, there is an event handler "on" defined in the v-tooltip component that is called when an event occurs in the slot. Yes, you have to maintain the binding of the event handler and the event trigger in the topmost parent component, but what's important - You don't have to define the event handler method in the topmost parent, but it can be defined in the component that contains the slot. This approach uses the scoped slots functionality: My code looks like this: DataProvider.vue <template>
<div>
<slot :loading="loading" :items="items" :total="total" :update="update">
{{ JSON.stringify(items) }}
</slot>
</div>
</template> <script>
export default {
name: 'DataProvider',
components: {
},
props: { 'table': String },
data () {
return {
loading: false
}
},
computed: {
items() {
return this.$store.getters[this.table];
},
total() {
return this.$store.getters[`${this.table}Total`];
},
},
watch: {
},
methods: {
update(params) {
/* LONG UNIMPORTANT EVENT HANDLER USING VUEX */
}
},
created () {
},
mounted () {
this.update();
}
} Traits.vue <template>
<data-provider table="traits" v-slot="i">
<traits-table :items="i.items" :loading="i.loading" :total="i.total" @update="i.update"/>
</data-provider>
</template> As you can see, I pass the update method to the slot component as a parameter, then I bind it to the evnet on the component in the slot in the parent of the DataProvider and it works. I hope this helps somebody. |
Just another usecase that would be immensely simpler if this was possible:
Now the wheel event gives you positional information relative to a) the element the event was registered to and b) the element the event originated from. If there are multiple layers of components below there is no way to get the information relative to the actual zooming target (which by definition has to be a single css transformable html element, which also happens to be a valid target for events). |
This does work for simple Parent<File-Picker>
<div class="clickme">Click me</div>
</File-Picker> File-Picker Component<template>
<div class="file-picker-wrapper">
<input
style="display:none;"
ref="filepicker"
type="file"
accept="image/png, image/jpeg"
/>
<div @click="openFilePicker" v-if="$slots.default.length">
<slot />
</div>
</div>
</template>
<script>
export default {
methods: {
openFilePicker() {
this.$refs.filepicker.click();
},
},
};
</script> Still +1 on slot event registration, but in case someone comes across this thread for something simple like me the answer might also be simple. |
Kind of breaking the meta here I assume, but what if there was a way to just have the markup that goes in a slot reference the "execution context" in which it was declared. For example, I have a card component that looks something like this:
And inside it I'm putting arbitrary content:
When I write We could cite a bunch of reasons why this is not a great idea, but the more re-usable and composable you make your markup the harder it is to pass things "up" or keep track of events. In my particular use-case this component is inside yet another component so when the click event fires: vue, I'm assuming, tries to find "addNew" in the methods of the I've read some of the approaches here, but the drawback I can see is that if we start defining every single method we might need inside a slotted component then its value as an abstract low-assumption component keeps diminishing. It would be nice if you could tell vue "look for the click handler in this context":
Then no matter how many levels down this markup happens to be in nested components it's not a problem for me to just define it relative to the context that is intuitive to me: the file where it is declared This was just a quick thought, I definitely welcome feedback on whether I'm missing some mechanic that would make this irrelevant. I have a feeling this would be very difficult to actually implement anyway, but food for thought I guess Edit: re-reading this kind of reminds me of the concept of currying, what's the currying equivalent for vue components? |
Check scoped slot. Assuming your carousel component has Carousel template:
Carousel example usage:
OR, use
Just in case if you like to see much expanded form of code instead of
Carousel example usage:
Answered the same here: https://stackoverflow.com/a/63671053/1292050 |
Anyone know if this is possible in Vue 3 ? I have this with the proper emit setup code, but it doesn't work.
|
@olfek No, this won't work, ChatGPT told me it'll work but after asking whether ChatGpt is right in this case on VueLand discord server, I was told this is not possible and ChatGPT is wrong. |
Okay I did it with custom non Vue event listeners. Why do limitations like this even exist 😞 - Let us "users" wield all the power, and decide how to use it, don't decide for us 😒 In the slotted component:
On a
Finally, implementation of
|
Could you please add a Vue way of doing the above please @yyx990803 , thank you 🙂 |
up for vue3 example. |
I came from non-vue background and found this offensive, do u have an example in https://codepen.io/ or in similar web? |
In vue3, I solve this issue by using provide('key', val) and inject('key') which imported from 'vue', both value and function can be provided and used, great success. Like React Context behavior. |
Emit does not work on This behavior is inconsistent. Both of these things host unknown children.
FYI - this is regarding Vue 3. I think I'll create a new issue. |
Not sure if we are having the same issue. So I needed to listen for an emit from a slot. This is the parent component that I need to listen to the emit:
Hope it helps |
I am not sure if this will help anyone, but since it was tough to find a solution for what I was doing, I am going to post this in a few places in hopes it helps anyone else.. I needed to send an emit from a slot, but at least in my situation, it was not working as it was a router-view from the main App component, in App, this simple solution works great, although it took me hours to figure out:
|
Vue.js version
2.1.3
Reproduction Link
https://jsfiddle.net/x8a3vvk2/8/
Events emitted from component inside slot are not received.
$emit('testevent') is not working but $parent.test() works.
The text was updated successfully, but these errors were encountered: