Attaching a function to a designated slot attribute

Currently, I am utilizing VUE 2.6.11 along with class components. My current objective involves encapsulating components that can serve as modals inside a separate component responsible for managing the modal state.

According to the documentation, it is possible to access child props/methods within a parent component using Scoped Slots. However, I am encountering an issue where my method fails to bind to a template:

In my Modal.vue file:

@Component
export default class Modal extends Vue {

  @Prop(String) icon !: string
  @Prop({ default: 'Open popup' }) tooltip !: string

  isVisible = false

  toggleModal() {
    console.log('toggleModal from Modal')
    this.isVisible = !this.isVisible
  }

  toggleModalFactory = 'simple property'
}

Template code snippet:

<div >
  <div v-if="isVisible" class="page overlay" >
    <div class="page-content" >
      <div class="dialog-content" >
        <div class="row col" >
          <slot :toggle-modal="toggleModal" />
        </div >
      </div >
    </div >
  </div >
  <button class="btn-primary btn-icon"
          :title="$t(tooltip)"
          @click="toggleModal()" >
    <i :class="icon" />
  </button >
</div >

Subsequently, in my Parent component, the following setup is implemented:

<modal icon="plus-icon" v-slot:default="modal" >
  <test-component :toggle-modal="modal.toggleModal" ></test-component >
</modal >

The development tools indicate that my method is indeed bound, as illustrated https://i.sstatic.net/QmQNr.png.

However, upon executing the prop function within my nested modal content (TestComponent.vue):

export default class TestComponent extends Vue {

  @Prop() toggleModal !: Function

  @Emit()
  dismiss() {
    this.toggleModal()
    console.log('dismiss from TestComponent')
  }

  @Emit()
  accept() {
    this.toggleModal()
    console.log('accept from TestComponent')
    return 'close-success'
  }
}

The following errors are produced:

[Vue warn]: Property or method "toggleModal" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

Additionally, there is an accompanying error message:

TypeError: this.toggleModal is not a function

While trying to troubleshoot, I came across this post, which leads to the same documentation I initially consulted. Unfortunately, I cannot identify any discernible difference that may be causing issues within my code.

Answer №1

One developer's tragic tale:

In a harrowing turn of events, my TestComponent found itself without the crucial @Component annotation ...

<script lang="ts" >
import { Emit, Prop, Vue, Component } from 'vue-property-decorator'

@Component
export default class TestComponent extends Vue {

  @Prop(Function) close !: Function

  @Emit()
  dismiss() {
    this.close()
    console.log('dismiss from TestComponent')
  }

  @Emit()
  accept() {
    console.log('close', this.close, this)
    this.close()
    console.log('accept from TestComponent')
    return 'close-success'
  }
}
</script >

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

What is the best way to filter and sort a nested tree Array in javascript?

Looking to filter and sort a nested tree object for a menu If the status for sorting and filtering is true, how do I proceed? const items = [{ name: "a1", id: 1, sort: 1, status: true, children: [{ name: "a2", id: 2, ...

When the property "a" is set to true, it must also require the properties "b" and "c" to be included

I'm looking for a way to modify the following type structure: type Foo = { a: boolean; b: string; c: string; } I want to change it so that if a is true, then both b and c fields are required. However, if a is false or undefined, then neither b ...

The current value of React.createRef() is perpetually empty

Ever since I started working on this code, I've been encountering a problem that seems to have no solution. Here's what's going on: import React, { Component } from 'react'; export class InfoPaneArrow extends Component<InfoPane ...

Having trouble with the alignment of items in Vue?

Currently, I am using the Vue framework in combination with Vuetify library to develop a web page. The main issue I am facing is related to card alignment on the page. When there are only a few cards displayed, the alignment looks perfect but if the number ...

Implement a feature in Vue.js where clicking on the "add image" box will reveal an image upload box for

<template> <b-row> <b-col md="3" v-for="item in defaultValues" :key="item.id"> <b-form-group> <b-form-file accept="image/*" placeholder="Choose image. ...

Tips for resolving the error message "TypeError: Converting circular structure to JSON"

I had a straightforward query where I needed to select all from the aliases table. Everything was working fine until I ran npm update. TypeError: Converting circular structure to JSON public async fetchAliases(req: Request, res: Response): Promise< ...

transform JSON structure into an array

Is it possible to convert an interface class and JSON file into a list or array in order to work on it? For example, extracting the Racename from each object in the JSON file and storing it in a list/array. Here is the interface structure: interface IRunn ...

Is React Typescript compatible with Internet Explorer 11?

As I have multiple React applications functioning in Internet Explorer 11 (with polyfills), my intention is to incorporate TypeScript into my upcoming projects. Following the same technologies and concepts from my previous apps, I built my first one using ...

Sveltekit: Troubleshooting problem of refreshing when utilizing store and localStorage

I am currently working on persisting data using localStorage and have successfully achieved persistence. However, I notice that when I refresh the page, it initially displays a value of 0 before fetching the localStorage value. Is there a way for me to ins ...

Injecting services and retrieving data in Angular applications

As a newcomer to Angular, I am trying to ensure that I am following best practices in my project. Here is the scenario: Employee service: responsible for all backend calls (getEmployees, getEmployee(id), saveEmployee(employee)) Employees components: displ ...

The correlation between a TypeScript class and an interface bearing an identical name

I have been struggling to find clear documentation or explanation for the unique relationship between a TypeScript class and an interface that share the same name. What is the significance of having an interface with the same name as a class? Why does a ...

In Typescript, ambient warnings require all keys in a type union to be included when defining method parameter types

Check out this StackBlitz Example Issue: How can I have Foo without Bar, or both, but still give an error for anything else? The TypeScript warning is causing confusion... https://i.stack.imgur.com/klMdW.png index.ts https://i.stack.imgur.com/VqpHU.p ...

The function forEach is unable to handle the process of uploading multiple images to cloudinary

I'm facing an issue with uploading multiple images to Cloudinary from my Vue2JS front-end. I have successfully created a function that uploads a single image, but I am struggling with uploading multiple images using a forEach loop. upload(evt) { ...

Encountering difficulty when trying to define the onComplete function in Conf.ts. A type error is occurring, stating that '(passed: any) => void' is not compatible with type '() => void'.ts(2322)'

I have been developing a custom Protractor - browserstack framework from the ground up. While implementing the onComplete function as outlined on the official site in conf.ts - // Code snippet to update test status on BrowserStack based on test assertion ...

Configuring Vue.js watchers inside a for loop

Exploring the dynamic addition of watchers in Vue.js. The discrepancy between what is desired and what actually happens is demonstrated below in the commented section. As a casual coder, I believe my issue lies more in grasping JavaScript basics rather t ...

What is the procedure for obtaining FlowNode in the typescript ast api?

Trying to access and resolve foo and bar from the nodes variable. Upon examination in ts-ast-viewer, it is evident that TypeScript recognizes foo and bar within the nodes node under the FlowNode section (node -> initializer -> elements -> escaped ...

Tips for modifying the properties of variables within an array using JavaScript

I have an array that holds variables used to control a specific template. divisionsListToManipulate: ['showActivitiesSection', 'hideAssignActionplanDiv', 'displayProp ...

Verification of unique custom string

How can I ensure that a string follows the specific format of x.xx.xxxxx? The first character is mandatory, followed by a period, then two characters, another period, and finally any number of characters of varying lengths. ...

What category does a Fresh of Deno event fall under?

I'm currently working with Deno and fresh. When it comes to events in islands, what is the type for an event like the one below? export function Sample() { return ( <input type="file" onChange={(e) => ...} // What typ ...

Can you explain the meaning behind this TypeScript variable declaration syntax?

Can anyone explain the meaning of this code snippet: myCollection: Collection|any = null; I'm having trouble understanding it... Does it indicate that myCollection is set to type Collection, (which is an interface), with a default value of null? But ...