Utilizing Slots in Vue: Accessing Component Methods

I recently started working with Vue and am facing an issue with Vue slots. The component structure is as follows:

<template>
<div class="dropDown__container">
  <div
    v-show="isOpened"
    class="dropDown__content"
    style="display:none;"
  >
    <slot />
    <div class="dropDown__container-flex">
      <span
        class="dropDown__button"
        @click="hideDropDown()"
      >
        Clear
      </span>
      <span
        class="dropDown__button"
        @click="hideDropDown(true)"
      >
        Submit
      </span>
    </div>
  </div>
</div>

There is a method called hideDropdown within the component that I want to pass to the slot. Here is how I am using the slot:

<drop-down>
<div class="d-flex flex-row justify-content-between">
    <ul id="priceFromList" class="hintList hintList--left">
        <li class="hintList__item" v-for="price in lessThan(autocompletePricesDesktop, editableCriteria.Price.To)" @click="">
            {{ price }}
        </li>
    </ul>
</div>
</drop-down>

I want to be able to pass the hideDropdown method from the component to the slot and use it within the @click event for each li element. Is this achievable? Any assistance would be greatly appreciated. Thank you.

Answer №1

If you are using Vue 2.6 or higher, you can make use of the following code syntax:

It is possible to achieve this, although it may not be considered best practice. Here is how you can do it:

In your Parent component, you will bind the function to the slot

<slot :callableFunc="hideDropDown"/>

<template>
    <div class="dropDown__container">
      <div
        v-show="isOpened"
        class="dropDown__content"
        style="display:none;"
      >
        <slot :callableFunc="hideDropDown"/>
        <div class="dropDown__container-flex">
          <span
            class="dropDown__button"
            @click="hideDropDown()"
          >
            Clear
          </span>
          <span
            class="dropDown__button"
            @click="hideDropDown(true)"
          >
            Submit
          </span>
        </div>
      </div>
    </div>
  </template>

In your child component, you will use scoped-slots to access the binded function.

<drop-down>
<template v-slot:default="{ callableFunc}">
<div class="d-flex flex-row justify-content-between">
    <ul id="priceFromList" class="hintList hintList--left">
        <li class="hintList__item" v-for="price in lessThan(autocompletePricesDesktop, editableCriteria.Price.To)" @click="callableFunc()">
            {{ price }}
        </li>
    </ul>
</div>
</template>
</drop-down>

For more information, refer to the documentation https://v2.vuejs.org/v2/guide/components-slots.html#Scoped-Slots

Answer №2

My approach to enhancing modularity involves giving the dropdown-container the responsibility of deciding when to close the dropdown, while the slot-contained component emits an event to signal an action, such as selecting an item.

To implement this, I would have the container listen for an event on the slot:

<slot v-on:item-selection="itemSelected" />

... and a function to handle the selected value:

function itemSelected(price) {
  this.price = price;
  hideDropdown();
}

In this scenario, the event is named item-selection.

Subsequently, I would emit the event from the contained component:

<li class="hintList__item" v-for="price in lessThan(autocompletePricesDesktop, editableCriteria.Price.To)" @click="itemClicked(price)">

... along with a method within that component:

itemClicked(price) {
    this.$emit('item-selection', price);
}

I trust that this logic is clear and provides improved modularity :-)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the correct way to refresh v-for loops in Vue3?

Here is a brief overview of the project: We need to display an invoice card that contains details about an invoice. Users should be able to assign payments to the invoice and also remove them. These payments are stored as objects in an array. <tr class= ...

Can you explain the meaning of the code `@input="$emit('input', $event)" used in a Vue component?

I have come across some code that I am looking to revise: <b-input :value="value" @input="$emit('input', $event)" ref="input" :maxlength="maxlength"/> Can someone explain what @input="$emit('input', $event)" means? Where should ...

Executing a JavaScript file within the Meteor JS ecosystem

Is there a way to execute a JavaScript file on the server side in a meteor JS environment? Providing some background information: I am looking to automatically insert a document into a mongo database. While I know how to do this in meteor through event-dr ...

Tips for customizing the checked color of Material UI Radio buttons

If I want my radio button to be green instead of the default options (default, primary, secondary), how can I achieve that? I attempted to override the color using the classes prop like this: const styles = theme => ({ radio: { colorPrimary: { ...

Using various colors to highlight specific sections of a letter or number

I am striving to recreate the unique image shown below, particularly interested in achieving the multi-colored effect on the numbers. This aspect of having different colors for parts of the number is intriguing and I would love to learn how it's done. ...

How can the event listener be utilized with md-autocomplete?

I am currently in the process of developing an angularjs application that incorporates an autocomplete feature. One key aspect of this application is that certain fields cannot be populated until an item has been selected using the autocomplete function. ...

JavaScript WYSIWYG Algorithm

Despite my searches on SO, it appears that most questions revolve around simply making a div editable using contenteditable="true". I am interested in finding the most effective method for tracking all formatting tags applied to a document. Merely togglin ...

What is the best way to prevent a folder from being included in the next js build process while still allowing

I am faced with a challenge involving a collection of JSON files in a folder. I need to prevent this folder from being included in the build process as it would inflate the size of the build. However, I still require access to the data stored in these file ...

Switch the monitored variable's value in VueJS

` ` I have a data variable that is of boolean type, and I have included this in a watch hook. When the value changes to true, I execute certain tasks within the watch function and everything works perfectly.` `watch: {` ` boolVar: func ...

Pause for a brief moment before proceeding to the next task within the map

My situation involves having a list of usernames that represent accounts: let users = [ "user1","user2","user3","user4","user5","user6","user7" ] users.map(async (user, i) => { co ...

AngularJS - the element of surprise in execution sequence

Encountering a puzzling issue that exclusively affects Internet Explorer (any version) and not Chrome. An "items" array is stored within the "doc" object. Users have the capability to edit items, which essentially deletes the item but retains its content ...

Interacting with touch events in JavaScript on Android devices

I am facing an issue with my HTML page where a div is meant to function as an on-off switch momentarily. The functionality I have implemented looks like this: $('#btn').mousedown(function() { startAction() }) $('#btn ...

Issue with React: Children's state is altering the state of the parent component

Question : Why is it possible for a child component to change the state of its parent when each component has its own state? Below is the complete code for my app: import React, { Component } from 'react'; import { render } from 'react-do ...

Is it possible for me to manually access the vue-router parser?

Is there a way to access the vue-router parser in order to evaluate a link before navigating to it? In other words: Suppose I have the path /one/two/three but it is not currently the active path. I would like to check if that path matches any defined rout ...

Tips on mapping API response to the data attribute in Nuxt framework

I am currently in the process of modifying a section within a form. In this section, I will retrieve data using the content's id from an API. My goal is to map the returned data into an array in the data property so that it can be easily patched. Bel ...

What is the method for defining the current date variable within a .json object?

When using a post .json method to send an object, I encounter the following situation: { "targetSigningDate": "2021-09-22T21:00:00.000Z" } The "targetSigningDate" always needs to be 'sysdate'. Rather than manually c ...

Looking for guidance on where to find a functional code sample or comprehensive tutorial on working with ViewMetadata in Angular2

I am currently trying to understand the relationship between viewmetadata and the fundamental use of encapsulation: ViewEncapsulation, including ViewEncapsulation.Emulated and ViewEncapsulation.None. Here is a link for further information: https://angula ...

I'm struggling to activate the eventListener on several elements with the same className or ID. Unfortunately, only the initial child is being triggered in my current code implementation

Hello fellow developers, I'm facing an issue while working on a project. I have about ten menu items with the same ID, and I want to be able to edit each one when it is clicked. Here's what I tried using JavaScript: const menuElement = d ...

Using IF-ELSE statements in jQuery for DataTables

Is there a way to handle If else statements like method in the datatable plugin? Currently, when the 'data' variable returns a value, everything works correctly. However, if it is empty, I would like it to return either "from1" or "from2", which ...

Tips for displaying a modal to a user only once

I've developed a Flask application that enables multiple users to register and log in. To achieve this, I have incorporated sessions into my code. When new users land on the initial page, they are greeted with a modal introducing them to the platform. ...