Leverage parent slot variables within the Vue template slot

I have a basic FormComponent:

<template>
  <form>
    <fieldset>
      <slot />
    </fieldset>
    <span v-if="!isEditing" @click="edit()">Edit</span>
  </form>
</template>

<script>
export default {
  data () {
    return {
      isEditing: false,
    }
  },
  methods: {
    edit (state) {
      this.isEditing = !this.isEditing
    }
  }
}
</script>

When I include the component:

<FormComponent>
  <input value="Man" type="text" :disabled="!isEditing">
</FormComponent>

The input fields are correctly inserted into the component, but the :disabled="!isEditing" binding in the slot does not update based on changes to isEditing within the FormComponent.

The Vue documentation is informative, yet there may be gaps in addressing specific scenarios.

Answer №1

To bind data onto an attribute of the <slot></slot> tag, you need to use a prop like this:

<slot :isEditing="isEditing"></slot>

Vue will then create and expose an object with all the bound data when rendering the slotted component. Each attribute will have a property on this object.

You can access this object by adding an expression to the v-slot directive in this manner:

<FormComponent v-slot:default="slotProps">  

(Alternatively, you can use the alias # as shown: #default="slotProps".) You can access individual properties, such as isEditing, from this object using slotProps.isEditing:

<FormComponent #default="slotProps">
  <input value="Man" type="text" :disabled="!slotProps.isEditing">
</FormComponent>

The more common and versatile approach is to use the <template> syntax:

<FormComponent>
  <template #default="slotProps">
    <input value="Man" type="text" :disabled="!slotProps.isEditing">
  </template>
</FormComponent>

You can also refer to destructure slotProps for direct access to the properties:

<FormComponent>
  <template #default="{ isEditing }">
    <input value="Man" type="text" :disabled="!isEditing">
  </template>
</FormComponent>

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

Searching for multiple filtered items in Vue.js

When working with Vue js, searching through a list is straightforward. However, when dealing with a large dataset of 1000 records and needing to apply specific filters for user searches, I find myself at a loss. Is there a plugin or method that can help me ...

Creating a registration and authentication system using firebase

When using Google authentication with Firebase, is the Signup and Login logic the same? I am creating a page for user authentication but I'm unsure if I should have separate pages for signing up and logging in. This confusion arises from the fact that ...

How to obtain the current URL of an iframe?

After coming across what seems to be a similar question, I still have to ask for clarification because I couldn't find a clear answer. Allow me to elaborate on my project, I am working on an online store where we offer two types of products, The fi ...

Utilize the ng.IFilterService interface within a TypeScript project

I am facing an issue with a .ts file that contains the following code: module App.Filters { export class SplitRangeFilter implements ng.IFilterService { static $inject = ['$filter']; public static factory(): Function { ...

Combining a variety of animations within a mesh

Can someone help me understand this specific example in Three.js? The link is . I am facing some difficulties with the BlendCharacter.js file. this.load = function ( url, onLoad ) { var scope = this; var loader = new THREE.JSONLoader(); load ...

React web app experiencing an issue with MUI Drawer opening flawlessly but failing to close

Recently, I encountered an issue with my React app. I have a Navbar component that displays a Sidebar component when the screen is small, using Material UI for the Drawer functionality. The problem arises when clicking the hamburger icon to open the drawe ...

The AJAX request encountered an error while trying to send a POST request to the http://localhost/upload/undefined endpoint. The

I've been scouring the internet and testing for hours, but I'm still unable to identify the source of the error. I could really use some assistance here. I meticulously followed a tutorial on multiple file uploads with drag & drop functionali ...

A guide on extracting the parent element from a JSON object with Vue.js

I'm currently dealing with flattened JSON data and encountering difficulties in accessing certain parts of it. My goal is to utilize the accessible elements to retrieve their parent elements for display. I am able to determine the count of arrays with ...

Managing promises - updating database entry if it already exists

I'm encountering a new challenge with Promises. Objective: Update the database entry only if P_KEY exists. The current database is accessible through a module that has both get and put methods for the database, each returning a Promise. Approach: ...

Encountering Issues with Discord JS as Member Fetch Returns Undefined

I'm facing an issue with fetching specific server members by their user id in order to assign a role to them. I keep getting an undefined response each time. Even though this bot has administrator permission and all required intents are assigned, I a ...

Is there a way to verify that all CSS files have been successfully downloaded before injecting HTML with JavaScript?

I am looking to dynamically inject HTML content and CSS URLs using JavaScript. I have more than 3 CSS files that need to be downloaded before the content can be displayed on the page. Is there a way to check if the aforementioned CSS files have finished ...

Protractor: Moving further down the page

One issue I encountered is with a button on my page that becomes visible only when the user scrolls down. As a result, Protractor tests are throwing an error: UnknownError: unknown error: Element is not clickable at point (94, 188). I attempted to reso ...

Searching for ways to filter out specific tags using regular expressions

Can anyone provide a quick solution to help me with this issue? I am trying to remove all html tags from a string, except for the ones specified in a whitelist (variable). This is my current code: whitelist = 'p|br|ul|li|strike|em|strong|a', ...

What methods can I use to stop the styles of a child component from impacting those of the parent component

Is there a way to create CSS rules that achieve the following conditions? The parent component's CSS does not impact the child component The child component's CSS does not affect the parent component The child component is sourced from an exte ...

bringing in a js file with an import statement at the beginning

I am looking to import a file that brings in another file for use across multiple pages Here is my folder structure: js modules momentum-scrolling index.js about.js contact.js Contents of momentum-scrolling.js: import LocomotiveScroll from &a ...

Following the path of JavaScript function calls

As I explore my Chrome console, I find myself puzzled by the mystery of the JavaScript file that gets called when I import a file from my computer after clicking on an input file tag. It seems to happen without any clear indication of which method triggere ...

Checking forms using axios in the vuejs framework alongside laravel

I've encountered an issue with sending form data to my backend using Laravel for validation. The problem is that Laravel is not returning errors with a 422 status. Axios I'm making a simple axios post request to a URL and expecting a response i ...

Challenges compiling 'vue-loader' in Webpack caused by '@vue/compiler-sfc' issues

The Challenge Embarking on the development of a new application, we decided to implement a GULP and Webpack pipeline for compiling SCSS, Vue 3, and Typescript files. However, my recent endeavors have been consumed by a perplexing dilemma. Every time I add ...

Defining the scope of a variable that is accessed by multiple asynchronous callbacks

Utilizing the async.js library by Caolan McMahon and the jQueryUI progress bar, I am providing real-time feedback to users while multiple asynchronous calls gather data and populate elements in a complex graph. The lingering question is: What is the most ...

What could be the reason for the HTML canvas not displaying anything after a new element is added?

How come the HTML canvas stops showing anything after adding a new element? Here is my HTML canvas, which works perfectly fine until I add a new element to the DOM: <canvas class="id-canvas", width="1025", height="600"> ...