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

Having difficulty sending data to a controller through AJAX in Code Igniter. Can anyone help troubleshoot

I recently started learning PHP OOP and am currently using the Code Igniter framework. I encountered some difficulties in sending data to the controller using AJAX, so I attempted a simple test to check if AJAX was functioning properly, but unfortunately, ...

Leveraging PapaParse for CSV file parsing in a React application with JavaScript

I am encountering an issue with reading a CSV file in the same directory as my React app using Javascript and Papaparse for parsing. Below is the code snippet: Papa.parse("./headlines.csv", { download: true, complete: function(results, f ...

What could be causing the HTML5 canvas not to show up on the screen?

<!doctype html> <html> <head> <title>Canvas test</title> </head> <body> <script type="text/javascript"> c = getElementById('canvas'); ctx = c.getContext("2d")' ctx.fillRect(10,10,10,10); </s ...

AngularJS does not allow data to be deleted in mongodb

Backend code: var User = require("./models/user"); var express = require('express'), app = express(), Account = require("./models/account"), mongoose = require('mongoose'), passport = require("passport"), basicAuth = require('basi ...

The dimensions of the pop-up window in Chrome's JavaScript are not displaying correctly

My goal is to launch a new chat room window on our website. The dimensions of the chat room are set to 750px x 590px. Below is the link I am using to trigger the javascript popup. <a href="javascript:void(0)" onclick="window.open('http://gamersuni ...

Searching for a specific value in an array with jQuery: A step-by-step guide

I am looking to search for a specific value within an array and retrieve its index. Sample HTML: <div class="container"> <div class="col-md-6"> <div id="task0">Task0</div> </div> <div class="col-md-6"> &l ...

I am looking to pass several parameters through the post method by utilizing ajax

Can someone assist me with this code? I am trying to pass the item ID, stock quantity, and price using AJAX in a POST method. Any help would be greatly appreciated. Thank you in advance! function updateItemDetails(itemId, sellingPrice, stockQty){ v ...

Python Selenium : Struggling to locate element using ID "principal"

As part of my daily work, I am currently working on developing a Python Script that can automate the process of filling out forms on various websites. However, I encountered an issue with Selenium while trying to interact with certain types of webforms. F ...

The JavaScript slideshow fails to display an image during one rotation

The slideshow displays a sequence of images from pic1.jpg to pic8.jpg, followed by a 4-second pause with no image, and then repeats starting again at pic1.jpg. I am looking to have it loop back to pic1.jpg immediately after displaying pic8.jpg. Below is t ...

Retrieving the row id of a selected item using Quasar Framework's data tables

I am looking for a way to remove a row from a quasar-framework datatable. My goal is to pass the id of the selected row(s) to a delete function, which will then use axios to request the deletion of data with these id(s). However, I am unsure of how to pr ...

Update the image on a webpage within a template using AJAX code

I manage a website that utilizes templates. Within the template, there is a main image that I need to replace on specific pages, not throughout the entire site. I am seeking a way to change this main image to a new one on select pages using Ajax. Upon re ...

Vuex has reserved this keyword

I am working on a Laravel application with the following code in app.js: require('./bootstrap'); window.Vue = require('vue'); import { store } from './store/store' import Sidebar from './Sidebar' Vue.component(& ...

Utilize a function from a separate JavaScript file by calling it within the $(document).ready(function()

Refer to this post for more information: Click here I attempted to access a function that was defined in another .js file based on the instructions from the post. However, I encountered an issue. Take a look at my code below: sildemenu.js $(document).re ...

Critical bug discovered in fundamental Vue.js component by Internet Explorer

My Vue.js-powered application is performing flawlessly in all web browsers, except for one... Upon attempting to launch it on Internet Explorer, a frustrating error appears: An anticipated identifier in vue.min.js, line 6 character 4872 Locating the spe ...

Mastering jQuery ajax in Google Chrome Extensions

I have developed a script to fetch data from an external server using JSONP request in jQuery. Please take a look at the code snippet below: $("#submit").click(function() { var state = $("#state").val(); var city = $("#city").val(); $.ajax({ ...

Unable to transmit props through components with Vue router

Hey there, I'm currently facing an issue with passing props from my vue router. It seems like nothing is being printed and when I checked in the mounted hook, it's returning undefined. However, strangely enough, when I use console.log(this.$route ...

Tips on deobfuscating Next.js HTML from online sources

I am faced with the task of reconstructing a website that I scraped from the internet using wget. It seems to be built on next js, based on the presence of the _next folder. Even though I have no experience with nextjs and do not understand its inner worki ...

Rearrange the elements in an array containing objects

I am working with an array of objects: const array = [ { id: "5a2524432b68c725c06ac987", customOrder: 1, name: "One", }, { id: "5a2524432b68sgs25c06ac987", customOrder: 2, name: "Two", }, { id: "5a252wfew32b68c725c06a ...

How can I replicate the function of closing a tab or instance in a web browser using Protractor/Selenium?

I want to create an automated scenario where a User is prompted with an alert message when they try to close the browser's tab or the browser itself. The alert should say something like "Are you sure you want to leave?" When I manually close the tab ...

The charts created using chartjs-vue display no data

After following some examples to create a test chart, I am facing an issue where the chart renders blank with dummy data. https://i.sstatic.net/RD77S.png My initial suspicion is that maybe the options are not being passed for the lines, but it seems like ...