Leverage the properties from a slot in Vue to use as local component data

Hello, I am currently using a layout that contains a slot where I render my pages. The layout fetches some data when rendered and passes it to the slot as props. While I can easily access the props within the template, I'm unable to use it as local data. My intention was to utilize this data as a filter while fetching additional data.

<template lang="">
    <Layout v-slot:default="{ apptAccess }">
        <h1>{{ apptAccess.ticketStatus }}</h1>

        <h1>Mentors</h1>
        <div class="grid grid-cols-4 gap-5 mx-auto my-10">
            <div class="mx-auto" v-for="Person in persons">
                <PersonCard :PersonDetails="person" />
            </div>
        </div>
    </Layout>
</template>
<script>

data() {
        return {
            mentors: [],
            apptAccess: null,
        };
    },

I've encountered an issue with not being able to access the slots. Any assistance on resolving this matter would be greatly appreciated. Thank you!

Answer №1

Vue SFC Playground

Use defineExpose() to expose your data to the parent component and access it through a template ref:

Layout.vue

<script setup>
import {reactive} from 'vue';
const apptAccess = reactive({});
defineExpose({apptAccess});
setTimeout(()=>Object.assign(apptAccess, {ticketStatus:'Ticket status: ok'}), 1000);
</script>

<template>
  <div>
    <slot v-bind="{apptAccess}"/>
  </div>
</template>

App.vue

<script setup>
import Layout from './Layout.vue';
import {ref} from 'vue';
const $layout = ref();
setTimeout(() => alert($layout.value.apptAccess.ticketStatus), 2000);
</script>

<template lang="">
    <Layout ref="$layout" #="{apptAccess}">
        <h1>{{ apptAccess.ticketStatus }}</h1>
    </Layout>
</template>

But there is a more efficient method of lifting the state to the parent component and accessing it in the child using either provide/inject or v-model. It's always better when the data fetch is done within the parent component to avoid mutations outside its scope.

Vue SFC Playground: provide/inject example

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

In Vue js, a continuous function is executed to check the user's current online or offline status

Hey everyone, I'm looking for a method to determine the online/offline status of users on my web application and constantly monitor it. If a user goes offline, I want to wait 10 seconds to see if they come back online. If not, I need to trigger a spec ...

Laravel's Vue component is experiencing issues with loading Axios response data

Hey everyone, I hope you're all doing well! I'm facing a bit of an issue with passing data from an axios response to the data property. The data is successfully fetched from the database and displayed in the console, but when I try to display it ...

Vue/Vuex - using async dispatch for AJAX requests in multiple components

I am working with vuex and using a store module to load user lists in my app through ajax. After the list is loaded, it doesn't fetch again if it's already present in the vuex store. I have implemented this logic in the main application layout as ...

Remove repeated selections in a dropdown menu using Vue JS

Could someone offer me some assistance, please? I have 3 dropdown menus that need to display specific subjects based on previous selections. One issue I'm facing is how to remove the initial selection in menu one from both menu two and menu three? I ...

What is the best way to send a JSON object in Vue.js?

<template> <div id="app"> <div id="bee-plugin-container"></div> </div> </template> <script> // import axios from "axios"; // import Bee from "@mailupinc/bee-plugin"; import $ from 'jquery' ...

Tips for writing unit tests for components using vitest in the latest version of Nuxt

I've been working on transitioning from Vue 3 to Nuxt 3. I've successfully written unit tests for my components using vitest in my Vue app, however, when running the same tests in the Nuxt app, I encounter the following error: Error: Failed to ...

can a computed property be delayed in its calculation?

Within the code snippet below, we can see that in the compPropsIsBtnDigitizePolygonDisabled function, it initially checks if the digitizePolygonInteractions variable is initialized. If it is not initialized, an error will be triggered. During execution, w ...

Having trouble navigating to the bottom of a VUEJS app?

I've been working on developing a chatbot app that utilizes a REST API to stream content. While the functionality of the app is running smoothly, I have encountered an issue with the scroll to bottom feature. Instead of automatically scrolling to disp ...

When a Javascript function marked as async is executed, it will return an object

Async function is returning [object Promise] instead of the desired real value. Interestingly, I can see the value in the console log. It seems like this behavior is expected from the function, but I'm unsure how to fix my code. This code snippet is ...

Utilizing markers for gaming in a data table with Vue and Vuetify

I am struggling to retrieve the games of teams from two objects with arrays in Vue. One object contains headers for a data table, while the other object contains status information. Despite my efforts, I have not been successful in fetching the game detail ...

"Customize the bar colors in Vuetify sparkline to create a unique and

In my vue/vuetify project, I have a sparkline component that displays bars representing values. I am looking to change the color of bars with values less than 0 to red. Here is a snapshot of what I have: https://i.stack.imgur.com/YvpFB.png Below is a simp ...

Refresh a component by utilizing Vuex getters

I have been attempting to trigger a re-render of a component, and I came across the suggestion of using key to force the re-render. I decided to go with this approach, setting my key as a value fetched from the store. However, even after committing a mutat ...

Learn how to read the contents of a v-textarea line by line with the help of JavaScript in V

In my v-textarea component, I have set the following properties: <v-textarea v-model="pmidInput" name="input-PMID" ...

Is there a way for me to customize the footer of the modal in Vue CoreUI?

I recently came across some code in the coreui vue template that looks like this: <b-modal title="Modal title" class="modal-success" v-model="successModal" @ok="successModal = false" ok-variant="success"> Lorem ipsum dolor sit amet, consectetur adip ...

Guide on incorporating dynamic markers into MapBox using Vue/Nuxt

After setting up my MapBox, I wanted to dynamically add markers using Vue/Nuxt. However, the markers are not appearing on the map and I'm unsure of what the issue could be. The code snippet below shows that console.log() prints the correct coordinate ...

Encountering a problem while running npm build (PostCSS plugin postcss-purgecss needs PostCSS 8) on vuejs3 with tailwind

I'm currently in the process of developing an application using Vue.js 3 and Tailwind CSS. While testing some configurations before diving into the project, I encountered a specific error message when running npm run build: ERROR Failed to compile wit ...

Expand or collapse level 1 nodes with v-treeview component

I have created a special button in my tree view that has the ability to toggle open and close all nodes within it. The button code: <v-btn @click="toggleTreeview" /> Here is my v-tree markup: <v-treeview :value="x" @inpu ...

The Vite build tool creates unique CSS module classes for each component

Is it possible to set the CSS module class name in the index.js file generated during the Vite build process? I am developing with multiple themes and a single-entry JS file. Currently, this is the output I get when trying to build the project: Index.js & ...

The difference between emitting and passing functions as props in Vue

Imagine having a versatile button component that is utilized in various other components. Instead of tying the child components to specific functionalities triggered by this button, you want to keep those logics flexible and customizable within each compon ...

How to manually add the $store parameter to a dynamically created Vue component that is missing it during creation

I'm a newcomer to the world of Vue/Nuxt and I've encountered an issue while attempting to dynamically generate a Vue component on button click using the following code: async addComponent(componentsItem) { var ComponentClass = Vue.component(&a ...