VueJS: Passing instance data to a method within an anonymous event handler situation - How to do it?

When testing the accessibility of Vue event binding to instance state/data, I encountered an issue. I attempted passing msg (instance data) into an anonymous function which then calls alertMsg(msg) (an instance method). However, it appears that only the default event object (in this case, a Mouse event) is being passed to alertMsg(msg), and not msg itself.

I even tried using (ev, msg), meaning I pass both ev (the event object) and msg as the second argument, but still only the event object is being passed.

Template

<div id="app">
  <p>{{ msg }}</p>
  <div @click="msg => { alertMsg(msg)}">test</div>
</div>

Vue Instance

new Vue({
  el: '#app',
  data() {
    return {
      msg: 'Hello World'
    }
  },
  methods: {
    alertMsg(e, msg) {
      console.log(e)
      alert(msg)
    }
  }
})

Any suggestions on how to solve this issue would be greatly appreciated.

Thank you!

Answer №1

To access special event variables, refer to the documentation for guidance:

https://v2.vuejs.org/v2/guide/events.html#Methods-in-Inline-Handlers

For example:

    <div id="app">
      <p>{{ message }}</p>
      <div @click="displayMessage($event, message)">test</div>
    </div>

If you need to access "message" directly within the function, use "this.message".

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

Combining the values of two objects and storing them in a single array

I want to write a program that compares 2 objects based on their properties and values. If the "name" property in both objects matches, I need to push that property and its value to a new object called value3. When value3 is logged, the response should lo ...

VueJS added a new object to the array, but the data did not update reactively

Here is my current data layout days: [ { id: 0 name: 'Monday', times: [] }, { id: 1 name: 'Tuesday', times: [] } } I have implemented the following function to append an object to the times array. onT ...

"Attempting to use a Chrome Extension to apply inline styles is not producing

Despite my attempts to search on Google, I have been unable to find a solution. I am currently working on developing a Chrome extension with the specific goal of changing/inserting the style.display property for one or more elements. This task would norma ...

Learn the best practices for incorporating jQuery and other JavaScript libraries in your Angular2 projects

Is it possible to integrate a demo showcasing Bootstrap carousel with CSS3 animations in Angular2 using HTML, CSS, and JS? I have created my own implementation in Plunker with Angular2, but I am facing issues with the animated inner content of the carousel ...

Obtain the YouTube video identifier from a YouTube embedded link

Is there a way to extract just the YouTube ID from a given URL? https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0 $(".youtube").click(function () { console.log(this.href.replace(new RegExp("em ...

Deleting a specific row within a Material UI DataGrid in Reactjs: Tips and tricks

As I embark on this React project, things are progressing smoothly. However, a challenge has arisen. The functionality I aim for is as follows: When the checkbox in a row is clicked, I want that particular row to be deleted. For instance, selecting checkb ...

Storing and retrieving a client-side object in Javascript: A step-by-step guide

Novice inquiry: I have created a basic draggable to-do list that saves its state in a single object containing tasks, containers, and index - currently, it is being stored in local storage. I am now delving into server-side development using express and ...

Should you include the dollar sign in a Vue HTML variable or not?

I’m a bit confused about whether or not I should include $ when using a Vue HTML variable: new Vue({ data: { a: "myData" } }); Do I need to use: <h1>My value is {{ a }}</h1> or <h1>My value is {{ $a }}</h1> What ...

Adjust text size using the "increase toggle"

I'm having trouble adjusting the font size of my text within the <div class="comment more>. Whenever I try to wrap the text in a <p>, the "more toggle" functionality stops working properly. Instead of revealing more text when I click on "m ...

Looking for an easy method to conditionally navigate to a different page in next, react js, or javascript. Any suggestions?

Looking for a way to dynamically route users to different pages based on form submission? One approach is to use a switch or if statement in the onSubmit function. Consider the following logic within the onSubmit function: (assuming that goTo() is a JavaS ...

Using jQuery to create clickable URLs within a rollover div

I am looking to have the div appear on a mouse over effect in the following code. Is there a way for me to input a url based on the data that is passed to it? Anchorage: ["Anchorage", "(555)555-5555"], (This represents the data being posted) AtlanticCit ...

What is the best way to show static files from the backend in a React application?

Currently, my setup involves a React application connected to an Express-Node.js backend through a proxy. Within the backend, there are some static files in a specific directory. When I make requests and embed the response link in the "src" attribute of an ...

Real-time chat system using PHP for one-on-one inquiries with server-sent events (not a group chat)

I'm currently working on developing a live chat inquiry form for a website using HTML server-sent events. I'm utilizing this tutorial as a foundation Here is my plan based on the tutorial: On the client side, users are prompted to enter a use ...

Merging a variable and its corresponding value in JavaScript

I am attempting to achieve a similar functionality in Angular javascript (with simplified code): var modelName = "date"; if (attrs.hasOwnProperty('today')) { scope.modelName = new Date(); } In the scenario above, my intention is for scope.m ...

Retrieve a value using the jQuery each() method

Hello, I am a beginner in JavaScript and I need help with extracting values from JSON and adding them to an array. My goal is to be able to parse this array using another function later on. However, I'm struggling with returning the array after adding ...

Struggles with handling asynchronous events in Angular

I'm currently working on a piece of code that iterates through an array containing 10 items. For each item, a request is made and the returned data is stored in another array. The entire process goes smoothly until reaching the line that contains $q.a ...

Showing a React Portal Toolbar only when populated with children

OBJECTIVE: The objective is to show the ToolkitArea only when there are children present in "#toolkitArea". CHALLENGE: Unable to accurately determine the number of children inside the ToolkitArea. ACTIONS TAKEN SO FAR: I have developed a component calle ...

The incremental BR tag counter seems to be malfunctioning, there appears to be a missing element

Can anyone help me with the following code? I'm trying to add an incremental counter next to each BR tag in a lyric song, but it doesn't seem to be working as expected. <?php $lyrics = "<p>Every time when I look in the ...

Utilize Next JS pages api to generate dynamic routes based on unique ids

In the content of my website, there is a collection of objects named stories that are displayed as an array. Additionally, I have a section where each individual story is showcased in detail. I intend to enable users to click on any story link within the ...

Error 403 with Google Search Console API: Access Denied

Currently, I am attempting to extract data from the GSC Search Analytics API using Python. Despite diligently following this resource, I have encountered an error that persists despite multiple attempts to remedy it: raise HttpError(resp, content, uri=se ...