Is it possible to generate a component dynamically using a string template?

I have a Component called "CDataTable" that renders columns in a for loop. Inside the loop, there is a template:

<template v-if="typeof col.template !== 'undefined'" #body="{data}">
    <component :is="compile(col.template)" :data="data" :value="getColValue(data, col.field)" />
</template>

In the parent component "LocationList," I can define the column definitions in an array of objects in the data():

columns: [
    {field: 'test', header: "test", width: 12, template: `<span v-if="typeof value !== 'undefined'">{{value}} <i class="pi pi-search" @click="console.log(this)"></i></span>`}
]

I managed to get the rendering working as shown above, but now I want to call a function of the ParentComponent "LocationList" in the click handler. Obviously, I have no access to the methods of "LocationList," so I thought I could emit an event and listen to it there. However, if I put "this.$emit" in the click handler, it shows an error that "$emit" is undefined.

So, I added a console.log(this) there to get a clue why. The reason is that "this" refers to the window object.

The question is: How can I call a function of the "LocationList" Component in the click handler?

Answer №1

Avoid using this within Vue templates, especially in inline event handlers.

If you input the column template (

<span v-if="typeof value !== 'undefined'">{{value}} <i class="pi pi-search" @click="console.log(this)"></i></span>
) into the online template compiler, the resulting output will be similar to the following (even though it's specifically for Vue 2, the appearance is almost identical in Vue 3):

function render() {
    with(this) {
        return (typeof value !== 'undefined') ? _c('span', [_v(_s(value)),
            _c('i', {
                staticClass: "pi pi-search",
                on: {
                    "click": function($event) {
                        return console.log(this)
                    }
                }
            })
        ]) : _e()
    }
}

The issue lies in the utilization of an anonymous function as a handler. For further clarification, refer to How to access the correct this inside a callback

Despite this, this is implicitly included in the templates thanks to with(this), enabling the use of $emit() within the handler...

Note: The method you are employing for column rendering seems unconventional. I'm uncertain about the functionality of your compile function, but it appears needlessly complex. If you intend to pass a template to a child component, utilizing slots would be more appropriate.

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

Using material-icons for cell rendering in ag-Grid with Vue

I am currently incorporating ag-Grid into a vuejs project. My goal is to render cells that display material icons, but unfortunately only the icon name appears instead of the actual icon: https://i.stack.imgur.com/9tV7B.png Below is the code for the &apo ...

Slider that allows range selection after midday

Currently facing a dilemma using the noUiSlider plugin. I have set up a time range picker starting from 6 am to 6 am the following day. Everything works smoothly until it reaches 23:59, but I need it to display 1:00, 2:00 instead of 25:00, 26:00 for the ...

SyntaxError: The input on line one ended unexpectedly and was not caught

This issue is commonly associated with messy close parentheses, however, the error is occurring on line 1 of the file! Below is the javascript code from (filename: calculate.js) var colors = new Array(); colors["SILVER"] = -2; ... Although there is m ...

Unable to reset the input value to an empty string

I have created a table with a search bar feature that filters the data when the search button is clicked and resets the filter to show unfiltered data when the clear button is clicked. However, the current input value is not clearing from the display even ...

Encountering a ReferenceError in Angular 4 due to d3 not being defined when importing in a module

I'm looking to incorporate these imports into my angular 4 app.module, rather than adding them directly to my index file. In app.module.ts -> import d3 from "d3"; console.log(d3) // Confirming successful import of D3 import nvd3 from "nvd3"; H ...

What could be causing my webpage to automatically refresh following a POST request in NodeJS?

Utilizing the express framework alongside NodeJS, I have encountered an issue where my client webpage refreshes after making a POST request that triggers a python script and returns a JSON object to the client. My dilemma lies in preventing this automatic ...

Manage the lineup of tasks in the bull queue by organizing them into groups

I am currently working on a nodejs application that handles queues using the bull library. The application is required to make multiple asynchronous HTTP requests and then process the results of these calls. I'm curious about whether bull would be an ...

In JavaScript, learn how to trigger a statement only when two specific events occur simultaneously

<html> <head> <style> div{ border: 1px solid black; width: 500px; height: 500px; } </style> <script> window.onload = function(){ document.body.onmousedown = function ...

Change the color of this element and input field background

Having trouble with setting the background color of an input field to red in this code: $(document).ready(function(){ $(".abc").focus(function(){ $(this).attr('background', 'red'); $("label").text('Insert tex ...

Blending an HTML jQuery toggle

Is there a way to make the current headline fade out while simultaneously fading in a new one when switching to the next div using a jQuery .html switch? Check out the codepen example: https://codepen.io/balke/pen/JpNNve $(window).scroll(function() { ...

What is the best way to divide React Router into separate files?

My routes configuration is becoming cluttered, so I have decided to split them into separate files for better organization. The issue I am facing is that when using 2 separate files, the routes from the file included first are rendered, but the ones from ...

Oops! The function 'ModalDemoCtrl' has not been defined, causing an error

Hey there, I'm encountering an error when using angularJS in my project. The project is built on the django framework and does not include any additional JS files. Here are some snippets of my code: JavaScript: {{ ngapp }}.controller("ModalDemoCtrl" ...

What is causing my function to not wait for the resolution of the Promise?

checkout.ts updateGlobalValue(){ updateShadowDomButton(); let globalValue = fetchGlobalValue() } web_component_render.ts let globalValue; async fetchData() { let booleanFromApi = await callToExternalAPI(); return booleanFromApi; } functi ...

Troubleshooting the issue of 'is not a function' in browsers when using TS Namespaces

Currently diving into the world of TypeScript, I've embarked on the journey of organizing my code into separate files. My primary file is structured as follows: // calculator.ts namespace Calculator { console.log(Calculator.operate(1,2,"+")) } In ...

What techniques can I implement with puppeteer to efficiently warm up the cache?

I have a lengthy txt document containing around 1000 URLs that need to be accessed in order to warm up the Varnish cache. Since Puppeteer is required, it's crucial that there is important content loaded through AJAX calls. This is my initial attemp ...

What is the best lifecycle hook to use for initializing components?

Below is an example where I am using the created lifecycle method to subscribe to the event service. Is this a common practice? Are there better or more appropriate ways or lifecycle methods to achieve the same functionality? const ViewComponent = { d ...

Learn how to dynamically apply a CSS attribute for a set period of time using jQuery and automatically revert it back to its original state after 2 seconds

Is there a way to apply a CSS attribute to a specific element (like a div) for only 2 seconds? Here is what I have tried so far: HTML: <div class="custom-div">bar</div> <input class="button" type="button" value="press me" /> JQuery: $ ...

What is the best way to retrieve the ID of a post request using React's axios hook?

My goal is to make a post request to create an app, and then establish its links. To achieve this, I need to obtain the id of the newly created items in order to create the links. Is there a way to retrieve the id of the item created through the post reque ...

The presence of #xfbml=1 is leading to some issues

Within my website, I am utilizing two distinct mechanisms incorporating both xfbml and fbjs: An FB:Like tag for individual entries The FB object for Facebook logins with FB connect The issue arises when "all.js" is included on the page, as the login scr ...

Is it possible to prevent a webpage from being refreshed?

I need help with an HTML page that puts the worker on pause time which will be subtracted from his/her day job. The issue is that when he/she refreshes the page, the timer starts from the beginning automatically. I want it to continue without resetting. Is ...