Understanding how to utilize the scoped slot prop within a parent computed property

Currently, I have a closely connected pair of parent-child components utilizing a scoped slot. The child component sends data to the parent through a scoped slot prop (which we'll refer to as myScopedProp). Everything is functioning smoothly in this setup. Within the parent's scoped slot, I am able to pass myScopedProp as an argument to various methods in the parent script and it works perfectly.

Now, my question is: How can I access myScopedProp within a computed function defined in the parent component without having to first set it as data? Is there a Vue.js native way to retrieve myScopedProp from the parent script?

<!-- parent -->
<template>
  <child>
    <template #theSlot="{ myScopedProp}">
      {{ parentMethod(myScopedProp) }} <-- this works fine
    </template>
  </child>
</template>

<!-- child -->
<template>
  <slot name="theSlot" :myScopedProp="someChildValue">
</slot>
</template>

So far, I have been resolving this issue by passing a method from the parent to the child which then sets the value of myScopedProp in the parent's data. However, this approach feels incorrect and redundant considering that the value is already being passed via the scoped slot.

Answer №1

VUE SFC PLAYGROUND

When it comes to achieving this task, there are numerous possibilities to explore. Personally, I prefer utilizing the provide/inject method given how closely intertwined the components are. This approach is often referred to as lifting state. Alternatively, the use of v-model could also be sufficient.

Other alternatives include:

  1. Directly assigning the value, similar to your attempt with a function
  2. An alternative and potentially more idiomatic solution would involve making use of the defineExpose() macro and a component reference:
<script setup>
import { ref, provide, cloneVNode } from 'vue';
import Comp from './Comp.vue';

const slotProp = ref();
const $comp = ref();
const providedProp = ref();
provide('providedProp', providedProp);

</script>

<template>
  <h1>{{ slotProp }}</h1>
  <h1>{{ $comp?.prop }}</h1>
  <h1>{{ providedProp }}</h1>
  <comp ref="$comp" #="{prop}" v-assign="comp => directiveProp = comp.internal">{{ (slotProp = prop, '') }}</comp>
</template>

Comp.vue:

<script setup>
import {ref, inject} from 'vue';
const prop = ref('Slot prop');
const exposed = ref('Exposed prop');
defineExpose({prop: exposed});
const provided = inject('providedProp');
provided.value = 'Provided prop';

const changeProps = () => {
  [prop, exposed, provided].forEach(r => r.value += ' changed')
};
</script>

<template>
  <div>
    <slot v-bind="{prop}"/>
    <div>
      <button @click="changeProps">Change props</button>
    </div>
  </div>
  
</template>

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

Learn the process of flipping an element when a button is clicked!

I want to use the jquery flip.js library to flip an element. However, I only want the element to flip when I click on a specific flip button, and then flip back again when another button is clicked. Any suggestions on how to achieve this functionality? ...

The declaration of 'exports' is not recognized within the ES module scope

I started a new nest js project using the command below. nest new project-name Then, I tried to import the following module from nuxt3: import { ViteBuildContext, ViteOptions, bundle } from '@nuxt/vite-builder-edge'; However, I encountered th ...

Integrate jQuery into a Vue.js 2 project using the expose-loader plugin

For my latest Vue.js project using the vue-cli, I attempted to import jQuery with expose-loader. Following the instructions in the official documentation, but unfortunately, I was not successful. Here are the steps I took: Installed jQuery and expose- ...

Setting a menu item as active in a SvelteKit app: A step-by-step guide

I encountered an issue with the main navigation menu in my sveltekit application. The problem is that when the app is loaded or refreshed, the active menu item corresponding to the current URL is not set. After struggling to find a solution online, I manag ...

Converting October website pages' formatting into JSON for a Vue.js application

In order to create a Vue menu in OctoberCMS, I have developed a plugin that extracts the page structure from October pages into JSON data while maintaining the indentation of pages and subpages. Referring to this post: How to get static page dropdown in O ...

Accordion checkbox with dynamic features

Currently, I am dynamically populating data into a jQuery accordion. My goal is to include a checkbox just before the <h2> text. <div id="checkbox"> <h2> <span> <input type="checkbox" class="mycheck" value="apple" / ...

The ng-click event in AngularJS does not function as expected when nested within another ng-repeat loop

I am facing an issue with ng-click in my Angular application (version 1.0.4). The first ng-click works fine, but the second one does not. <div class="menu-group" ng-repeat="module in modules"> <div ng-click="toggle($event, $parent)" ...

Checking the opacity with an if/else statement, then adding a class without removing the existing class

This function is designed to check the opacity of the header, which fades out as a user scrolls down. If the opacity is less than 1, it disables clickability by adding the class "headerclickoff". However, there seems to be an issue with removing the clas ...

Looking for a way to assign customized thumbnails to images in react-responsive-carousel and react-image-magnifiers?

I am currently working on a product viewer using react-responsive-carousel and react-image-magnifiers. Following an example from this GitHub repository, I encountered an issue with mapping custom thumbnails correctly. Although hard-coding the array works f ...

Generating output from a callback function in TypeScript

When I execute a graphql query, the showUsers function is supposed to display all users (styled as boxes). However, at the moment, nothing is showing up. I am utilizing a functional component instead of a class component. This function is invoked after m ...

What is the best way to prompt users to submit comments with a popup textarea box?

Within my project, I have incorporated a dropdown list: <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select subject <span class="caret"></span> </but ...

Sorting through an array of objects based on a key and value that match another object

Is it possible to filter or query an array with the following structure? [ { 'xml:id': 'Name1', sex: { '$t': 'M' }, occupation: { n: 1 ...

After successfully posting a tweet, I have not heard back from Twitter

My objective is to achieve the following on click: Share the URL and text on Twitter in a popup window Receive a response from Twitter indicating whether the tweet was successful or failed Close the popup window after the tweet is successfully pos ...

Pagination with composite queries in Firestore allows for efficient retrieval of

Currently I am attempting to paginate a composite index query, let size = data.length let lastElement = data[size-1].commentCount db.collection('user-content').orderBy('commentCount','desc').orderBy('likes', 'd ...

Exploring the potential of Angular JS and gapi in building a seamless routed

I'm facing a similar challenge as described in this question. However, the key difference is that I require two controllers for two distinct routes, essentially representing two different tables: ../table1 and ../table2. Each table needs to fetch data ...

Chrome is having trouble setting the cookie with the Set-Cookie header

I am making an AJAX call to another service's API, expecting to receive a cookie that will be stored in my browser for future API calls. Unfortunately, even though the response headers contain a 'Set-Cookie' header, the cookie is not being s ...

An improved solution for avoiding repetitive typeof checks when accessing nested properties in the DOM

One common issue I encounter when working with nested DOM objects is the risk of undefined errors. To address this, I often use a conditional check like the one shown below: if("undefined" != typeof parent && "undefined" != typeof parent.main ...

Developing a matrix arithmetic parser using JavaScript

Currently, I am in the process of developing a program that can solve matrix equations. My main focus right now is on making sure the parser functions correctly. However, I am feeling lost and unsure of where to begin. In my program, I utilize an array of ...

ngSanitize continues to present plain text rather than rendering HTML code

When working with AngularJS scope, I encountered the need to display certain items as HTML. After some research, I realized that integrating ngSanitize was necessary for this functionality. Here is how I implemented it in my app: <script src="Scripts/a ...

How can MakeStyles be used to change the fill color in an SVG file by targeting specific IDs with Selectors?

Consider the following scenario: Contents of SVG file: <g transform="translate(...)" fill="#FFFFFF" id="Circle"> <path ........ ></path> </g> <g transform="translate(...)" fill="#FFFFFF" id="Circle"> &l ...