Can $event be transferred from cshtml to Vue.component?

I am facing an issue when trying to pass an event into my Vue component. No matter what method I try, I keep getting a "TypeError: Cannot read property 'preventDefault' of undefined" error.

Here is the code snippet for my Vue component:

Vue.component('jl-asset-list', {
created() {
    console.log(this.asset);
    console.log(this.canModify);
    console.log(this.editSiteAssetAllowed);
    console.log(this.event);
},
props: {
    hasCompleteTask: {
        default: false,
        type: Boolean
    },
    asset: {
        type: Object,
        required: true
    }
},
methods: {
    EditSiteAsset(asset, event) {
        event.preventDefault();
        event.stopPropagation();

        var context = this;
        context.SelectedSiteAsset = asset;

        var target = event.target || event.srcElement;
        var icon = $(target).closest('.jobasset_edit');

        icon.prop('disabled', true);
        this.$emit('edit-site-asset', asset);
    },
    EditJobAsset(asset) {
        this.$emit('edit-job-asset', asset);
    },
    HighlightAsset(asset) {
        this.$emit('highlight-asset', asset);
    }
}

Below is the relevant part of my CSHTML:

<jl-asset-list v-for="(siteAsset, index) in FilteredSiteAssets" 
                                           inline-template 
                                           v-bind:asset="siteAsset" 
                                           v-bind:canModify="Model.CanModify"
                                           v-bind:editSiteAssetAllowed="Model.EditSiteAssetAllowed"
                                           v-on:highlight-asset="HighlightAsset" 
                                           v-on:edit-site-asset="EditSiteAsset">
                                @Html.Partial("~/Views/Asset/Templates/_AssestList.cshtml")
                            </jl-asset-list>

This is how I have defined my template:

<a v-on:click="EditSiteAsset(asset)" 
       class="jobasset_edit jl-icon-orange" data-toggle="tooltip" data-placement="top" data-original-title="Edit">
        <i class="mdi mdi-pencil-circle mdi-24px"></i>
    </a>

I have also tried using EditSiteAsset($event) in v-on and emitting 'edit-site-asset' from the Vue component, but it doesn't work either.

The EditSiteEvent() method within my Vue component requires an event to function properly.

EditSiteAsset: function (data, event) {
        event.preventDefault();
        event.stopPropagation();

        var context = this;
        context.SelectedSiteAsset = data;

        var target = event.target || event.srcElement;
        var icon = $(target).closest('.jobasset_edit');

        icon.prop('disabled', true);

        GetSwitchModalPartial(
            '/Asset/UpdateSiteAsset?siteId=' + context.Model.SiteId + '&id=' + data.Id,
            { forJobAsset: true },
            function (data) {
                icon.prop('disabled', false);
            });
        return false;
    },

Answer №1

    <a v-on:click="UpdateSite(asset, $event)">
        <i class="mdi mdi-pencil-circle mdi-24px"></i>
    </a>

$event is not considered a "prop" in traditional Vue terminology; it is simply a special keyword that allows you to pass the DOM event when setting up an inline DOM event listener.

Furthermore, you can eliminate the following code from your event handler:

event.preventDefault();
event.stopPropagation();

If you utilize event modifiers like this:

    <a v-on:click.prevent.stop="UpdateSite(asset, $event)">
        <i class="mdi mdi-pencil-circle mdi-24px"></i>
    </a>

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

Selecting options on hover, either A or B at the least

I need a jQuery selector to handle an 'either' scenario. Specifically, I have a dropdown menu and want it to stay open when the user hovers over either of two elements. Either when they hover over the button or when they leave the popped-out men ...

Mastering the utilization of the Data object in VueJS with Decorators can be tricky. One common error message you might encounter is, "Class method 'data' expected 'this' to be used."

Error > The class method 'data' should use 'this' but it is not. I encountered this issue and believed I fixed it as shown below: TypeScript Unexpected token, A constructor, method, accessor or property was expected <script lang ...

Attempting to access a variable without wrapping it in a setTimeout function will

I have a form without any input and my goal is to automatically set the "responsible clerk" field to the currently logged-in user when the component mounts. Here's what I have: <b-form-select v-model="form.responsible_clerk" :op ...

"Using Nightwatch.js to Trigger a Click Event on a Text Link

My goal is to use Nightwatch for testing the login process by clicking on a log in text link. I came across this helpful article: How to click a link using link text in nightwatch.js. The article suggested using the following code: .useXpath() // ever ...

Triggering the body onunload event

I am currently developing a HTA that needs to make final modifications on the onunload event. However, I am facing an issue as the event does not appear to be triggered. Can someone confirm if this event is still supported? Is there an equivalent event in ...

Using setTimeout or setInterval for polling in JavaScript can cause the browser to freeze due to its asynchronous

In order to receive newly created data records, I have developed a polling script. My goal is to schedule the call to happen every N seconds. I experimented with both setTimeout() and setInterval() functions to run the polling task asynchronously. However ...

View a pink map on Openlayers 2 using an iPhone

I am currently working on a project where I am trying to track my location using my smartphone and display it on a map. To achieve this, I am utilizing openlayers 2. However, I am encountering an issue. When I implement the code below in a Chrome Browser ...

Ensuring compatibility of peerDependencies through devDependencies in npm3

With the recent update to NPM 3, automatic resolving of peer dependencies has been removed. This poses a challenge when developing a plugin/library for consumption by another application. If the underlying library uses peerDependencies, it requires manual ...

Attempting to insert a square-shaped div within a larger square-shaped div and enable it to be moved around by dragging

Imagine this scenario: I have a button and a large div. When the button is clicked, the code adds a new div inside the larger one. However, the new div is not draggable because I didn't implement the necessary code. I'm also trying to figure out ...

Transferring attributes from grandchildren to their ancestor

My React.js application structure looks like this: <App /> <BreadcrumbList> <BreadcrumbItem /> <BreadcrumbList/> <App /> The issue I am facing is that when I click on <BreadcrumbItem />, I want to be able to ch ...

Rotation snapping feature 'control.setRotationSnap' in TransformControls.js (Three.js) is not functioning properly

Attempting to utilize the functionality of "control.setRotationSnap" from the script "TransformControls.js", but unfortunately, it is not working as expected. After conducting some research, I came across a forum post suggesting that the code might not be ...

Executing a complex xpath using Java Script Executor in Selenium WebDriver

When working with a large grid and trying to find an element using XPath, I encountered some difficulties. The XPath used was: By.xpath("//div[contains(text(),'" +EnteredCompetitionName+ "')]/preceding- sibling::div[contains(concat(' &apo ...

Ways to enable file/result downloads on a website using HTML

Could you please take a look at this repository: https://github.com/imsikka/ArtGallery I am looking to create a downloadable result using a download button. I can create the button, but I am unsure of how to make the file actually downloadable. Do I need ...

Vue.js - display additional items in an array with matching titles

I am working with an array of objects, examples include: [{ title: 'foo' id: 1, name: 'anne' }, { title: 'example', id: 2, name: 'anne' }, { title: 'ex', id: 3, name: &a ...

Issue with Chart JS: Firefox is reporting that the 'Chart' is not defined

As a newcomer to Chart JS, I am currently utilizing it in Angular JS version 1.5.3 with Chart JS version 2.1.4. Below is the code snippet I am working with: var myChart = new Chart(ctx, { type: 'line', data: { labels: dates, datasets: [{ ...

Using Nuxt.js with Vagrant and Homestead for seamless port forwarding

I am encountering an issue where I can't seem to connect to my Nuxt.js application OUTSIDE of the vagrant box (i.e., on my host or local machine), although it is able to fetch content INSIDE the vagrant box. Here's what I'm doing: I'v ...

I am unable to apply CSS to style my <div> element

I've run into a snag with my coding project, specifically when attempting to style my div. Here is the code I have so far: All CSS rules are applying correctly except for the .chat rule. Can someone help me figure out what I'm doing wrong? var ...

Do not proceed with the form submission if the fields are left blank

I am facing a challenge with organizing two sets of data, "heat" and "cold", obtained from an external provider. The data is messy and I have trimmed down the code to focus on the main issue at hand. Both "heat" and "cold" have properties that users need t ...

Ensuring precise accuracy in JavaScript; transforming 0.5 into 0.5000

My current challenge involves converting every fraction number to n decimal places in JavaScript/Node.js. However, I've encountered a roadblock as it appears impossible to convert 0.5 to 0.5000. This discrepancy is causing my test cases that anticipat ...

When utilizing the ::first-letter pseudo-element on <sub> and <sup> tags

Why is the <sub> and <sup> not supporting the ::first-letter CSS pseudo-element? Any solutions? p:first-letter, sub:first-letter, sup:first-letter { color: red; font-weight: bold; } <p>This text contains <sub>subscript</su ...