Error: Encountered an issue with converting a circular structure to JSON while attempting to access $slot data from a Child component in VueJS

Issue:

<pre>{{ $slots.title() }}</pre>
does not display the expected object.

This is the parent component

ModalView.vue

<script setup>
import { ref } from 'vue'
import Modal from '@/components/Modal.vue'
import { btnStyleDark } from '@/styles/tailwindStyles'

const showModal = ref(false)
</script>

<template>
  <div>
    <h1>Modals</h1>
    <button @click="showModal = true" :class="btnStyleDark">Show Modal</button>

    <Modal v-if="showModal" @close="showModal = false" :btn-style="btnStyleDark">
      <template #title>My New Title</template>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vel tempora quibusdam tenetur,
        debitis autem fugit a nesciunt mollitia ipsa inventore nostrum perspiciatis neque dolor id
        magnam facere eum similique? Adipisci.
      </p>
    </Modal>
  </div>
</template>

This is the child component

Modal.vue

<script setup>
import { defineProps, defineEmits } from 'vue'

const props = defineProps({
  btnStyle: String,
})

const emit = defineEmits(['close'])
</script>

<template>
  <teleport to="#modals-container">
    <div class="modal z-10 absolute top-0 left-0 w-full h-full p-10 bg-yellow-50">
      <h1><slot name="title" /></h1>
      <slot />
      <pre>{{ $slots.title() }}</pre>
      <button :class="btnStyle" @click="$emit('close')">Hide modal</button>
    </div>
  </teleport>
</template>

Error in Chrome:

TypeError: Converting circular structure to JSON --> starting at object with constructor 'Object' | property 'vnode' -> object with constructor 'Object' --- property 'component' closes the circle at JSON.stringify () at toDisplayString (chunk-U6BEPC57.js?v=60065120:256:154)

If I remove the () from

<pre>{{ $slots.title() }}</pre>
inside the child component, I can see this printed in the <pre> tag on the page without an error:

https://example.com/image1.png

However, this data does not provide any useful information and differs from the data displayed in the tutorial video:

Tutorial Image

Attempts to Resolve


Tested using the useSlots import

Produces the same error, but the first console.log statement works!

<script setup>
import { defineProps, defineEmits, useSlots, onMounted } from 'vue'

const props = defineProps({
  btnStyle: String,
})

const emit = defineEmits(['close'])

const slots = useSlots()

console.log(slots.title())

onMounted(() => {
  console.log(slots)
})
</script>

<template>
  <teleport to="#modals-container">
    <div class="modal z-10 absolute top-0 left-0 w-full h-full p-10 bg-yellow-50">
      <h1><slot name="title" /></h1>
      <slot />
      <pre>{{ $slots.title() }}</pre>
      <!-- <pre>{{ slots.title ? slots.title()[0] : '' }}</pre> -->

      <button :class="btnStyle" @click="$emit('close')">Hide modal</button>
    </div>
  </teleport>
</template>

Also attempted

<pre>{{ slots.title() }}</pre>
without the $, which still results in the error message being thrown.

Answer №1

It appears that null values are causing display issues in this scenario.

I am utilizing const slots = useSlots();

<div v-for="(value, key) in slots.title()[0]" :key="key">
  <strong>{{ key.toString() }}:</strong>
  {{ value ? value.toString() : "null" }}
</div>

During testing, I implemented a simple function:

<button @click="close">Hide modal</button>

function close() {
  console.log(slots.title()[0]);
  emit("close");
}

As a result, I observed similar behavior to what was shown in the Udemy screenshot.

A helpful tip: In Vue3, you need to declare the emit event without the '$', so instead of @click="emit('close')"

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

Guide to obtaining the root directory in order to send AJAX requests to a server

I am currently working on a small Node.js project where the client side will be making multiple AJAX requests to the server. I want the code to be able to work with any webpage, but I realized that the path is relative to the page's location. How can ...

Implement a sleek carousel within a Vue component

Hello, I am trying to add a single slick carousel component to a block that already contains 2 components in a template. However, when I do this, it distorts the images of the other component. <template v-if="isMobile"> <vue-slic ...

Adjust the Highcharts semi-pie design by eliminating the gap between the pie and the legend

I'm having trouble adjusting the spacing between the bottom of a semi circle donut chart in Highcharts and the legend below it. Despite my efforts, I have not been successful in reducing this gap. Here is the basic chart I am currently working on: h ...

I would like to connect the button to a different webpage

Is it possible to connect this code with page number 2? <div class="login"> <h1>Login</h1> <form method="post"> <input type="text" name="u" placeholder="Username" required="required" /> <input type="password" name="p" ...

Tips for showing a limited number of results the first time in an AngularJS application

I am a beginner in AngularJS and Ajax requests. I created a demo where I make an Ajax request to get remote data and display it in a list. My goal is to initially show only 10 results when the page loads for the first time, and then load the next 10 result ...

What signals to Angular that $httpBackend is substituting $http during the testing of AngularJS?

My factory, called myFactory, has a dependency on $http. When writing tests for this, I needed to mock this dependency. After some research, I discovered that I could accomplish this using $httpBackend. Implementing the code below successfully achieved t ...

Error in Node.js: Module 'chai' not found

I've been experimenting with an example I found on Completed this step: $ npm install -g mocha Resulted in: C:\Windows\system32>npm install -g mocha npm WARN deprecated Jade has been renamed to pug, please install the latest version o ...

Sharing information through a hyperlink to a Bootstrap popup window

I've been attempting to send data to a Bootstrap modal window with no success so far. First, I tried: <a href="#TestModal?data=testdata" role="button" class="btn" data-toggle="modal">Test</a> However, the modal did not open as expected. ...

An unexpected 'foo' key was discovered in the current state being processed by the reducer when using redux-toolkit's configure store and a customized store enhancer

I've been working on developing a custom store enhancer to add new values to my root state. However, I've encountered an unexpected key error after delving into the complexities of custom enhancers. While I can see the new state part in devtools ...

Passing JSON information from a website to a Node.js server

<script type="text/javascript" src="data.json"></script> var mydata = JSON.parse(data); data = '[{"yer" : "Besiktas", "lat" : "41.044161", "lng" : "29.001056"},{"yer" : "Eminönü", "lat" : "41.017513", "lng" : "28.970939"},{"yer" : "Zeyt ...

The ajax signal indicates success, yet there seems to be no update in the database

Hey there, thank you for taking the time to read this. Below is the code I'm currently working with: scripts/complete_backorder.php <?php if(!isset($_GET['order_id'])) { exit(); } else { $db = new PDO("CONNECTION INFO"); ...

How to scroll a section of a container that's fixed, containing nested flex containers using Vue and TailwindCSS techniques

Looking for some help here! I have an overlay container with a fixed attribute, and inside, I need three flex col divs to sit side by side. In the first flex-col div, I have a div at the bottom containing two components (also flex-cols) that I want to make ...

Utilizing the Loess npm module in conjunction with Angular 4

I am attempting to incorporate the Loess package into my project. The package can be found on NPM and offers various regression models for data fitting. I successfully installed it using npm install loess --save, and it now resides in the node_modules dire ...

The style was not applied from because it has a MIME type of 'text/html', which is not a supported stylesheet MIME type, and strict MIME checking is turned on

I'm currently working on creating a Google web app that relies on a Google sheet in the backend. I prefer to develop locally in VSCode since the editor in Google Apps Scripts is quite limited. Additionally, I aim to incorporate Vue3 into my project. ...

How to show only the tree panel node with a specific ID in ExtJS 4

MySQL Tree Database: CREATE DATABASE `tree`; DROP TABLE IF EXISTS `mytree`; CREATE TABLE `mytree` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'node_id', `text` varchar(20) NOT NULL COMMENT 'node_name', `parent_id` int(11) NOT ...

What are the steps I should take to resolve the unit test problem specific to my situation?

I have been encountering an issue while trying to unit test two functions, as I keep receiving an error indicating an undefined object. This is my controller: vm = this; //always fire first in the app vm.getCompany = function() { api.getCompany(funct ...

Enhance the active input field by adding value to it

What is the best way to enhance the active input field within a group of all the input fields? I attempted using the autofocus attribute on "the_field," but had no success. ...

Utilizing jquery to iterate through anchor tags, locate the class of the anchor being hovered over, and

Review the following block of HTML code: <div class="week start-available start-mid end-available end-mid overlap-False"> <a href="http://alink.com" class="20130906-20130912"> <span class="wk-start" sty ...

Utilizing React's useState Hook with Firebase's onSnapshot Event

Is there a way to automatically retrieve new incoming messages from a firestore collection using onSnapshot? I am able to update the state inside the callback function, but for some reason, I cannot access it. const [messages, setMessages] = useState(null) ...

The process of displaying a PHP variable on an HTML page by calling a PHP script

I have a PHP script and I need to access its variables in an HTML page using jQuery, JavaScript, or AJAX. Please assist me with implementing this script: <?php $sta = $matches[1]; $tm = $matches[2]; $c = $matches[3]; $v= $matches[4]; $a1= $matches[5] ...