Assigning a value to a variable from a method in Vue: a step-by-step guide

I'm having trouble assigning values from a method to variables in HTML. Here's what I have in my code:

<b-card-text>X position {{xpos}}</b-card-text>
<b-card-text>Y position {{ypos}}</b-card-text>

I would like to assign values to xpos and ypos from the following method:

methods: {
    show() {
      const canvas = document.getElementById('canvasId')
      
      canvas.addEventListener('click', event => {
        const rect = canvas.getBoundingClientRect()
        const x = event.clientX - rect.left - canvas.clientLeft
        const y = event.clientY - rect.top - canvas.clientTop
        
        const xpos = x
        const ypos = y
      })
    },
    

When trying to access xpos and ypos, I encountered an error:

'xpos' is assigned a value but never used
'ypos' is assigned a value but never used

Could you please advise me on how to properly assign values from this method?

Answer №1

To access and utilize the data object, you can seamlessly integrate it into both the template and methods sections.

data () {
    return {
        xpos: '',
        ypos: ''
    }
},
methods: {
    show() {
      const canvas = document.getElementById('canvasId')
      // canvasMouseTrack.width = 1024
      // canvasMouseTrack.height = 800
      // console.log(rect.offsetY)
      // console.log(rect.offsetX)
      // console.log(rect.width)
      canvas.addEventListener('click', event => {
        const rect = canvas.getBoundingClientRect()
        const x = event.clientX - rect.left - canvas.clientLeft
        const y = event.clientY - rect.top - canvas.clientTop
        // console.log('Pos x', x, ' Pos y', y)
        this.xpos = x
        this.ypos = y
      })
    },

Answer №2

data: () => ({
   positionX: 0,
   positionY: 0
}),
methods: {
    display() {
      const canvasElement = document.getElementById('canvasId')
      // canvasMouseTrack.width = 1024
      // canvasMouseTrack.height = 800
      // console.log(rect.offsetY)
      // console.log(rect.offsetX)
      // console.log(rect.width)
      canvasElement.addEventListener('click', event => {
        const boundingRect = canvasElement.getBoundingClientRect()
        const xCoordinate = event.clientX - boundingRect.left - canvasElement.clientLeft
        const yCoordinate = event.clientY - boundingRect.top - canvasElement.clientTop
        // console.log('Position x', xCoordinate, ' Position y', yCoordinate)
        this.positionX = xCoordinate
        this.positionY = yCoordinate
      })
    },

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

How to empty an array once all its elements have been displayed

My query pertains specifically to Angular/Typescript. I have an array containing elements that I am displaying on an HTML page, but the code is not finalized yet. Here is an excerpt: Typescript import { Component, Input, NgZone, OnInit } from '@angul ...

Utilize Javascript to access Django Rest Framework API and obtain a Token

I've successfully set up an API with Django Rest Framework that functions well when accessed through cURL, HTTPie, or the browsable API. The API utilizes token authentication, requiring initial credentials to obtain a token. To achieve this using HTTP ...

I am curious if there exists a VSCode plugin or IDE that has the ability to show the dependencies of TypeScript functions or provide a visual representation

Are there any VSCode plugins or IDEs available that can display the dependency of TypeScript functions or show a call stack view? I am looking for a way to visualize the call stack view of TypeScript functions. Is there a tool that can help with this? Fo ...

Develop a time-sensitive store system using HTML and JavaScript that toggles between open and closed status based on set

I am looking to develop a time-based Open/Closed store using HTML and JavaScript. The concept is that on Fridays, the element with id="friday" should be displayed, otherwise, show the element with id="week". Additionally, if the time i ...

Using node.js for synchronous callbacks in node.js programming

I am new to node.js, and from what I've gathered, each callback creates a new event that can be executed in parallel. For instance, consider the following code with a callback: function testFunction(var1){ s3.head(var1, function(data, err){ ...

Modify the onerror function of the image tag within the onerror function

Here is a way to display images using the img tag: If 1.jpg exists, show 1.jpg. If not, check for 2.jpg and display it if it exists. If neither 1.jpg nor 2.jpg exist, display 3.jpg. <img src="1.jpg" onerror="this.src='2.jpg'; this.oner ...

Problem with Jquery Ajax, failing to recognize option values

Hello everyone, please review the code snippet below... $.fn.myajax = function (options) { var defaults = { my_event: "", my_url: "", my_data: "", } var o = {}; var mydata = options.my_data; $.extend(o, default ...

Browse the string on the web browser

Is there a way for me to continuously read and capture a string as it is being written in the browser, retrieving its value every 5 seconds? I need to be able to monitor the changing value while it is being input. In PHP, I have the following code snippet ...

Running a JavaScript script after loading a page via AJAX is not functioning as expected

As I am attempting to retrieve a page using AJAX, I've encountered an issue where any Javascript code included on that page fails to execute. Why is this happening? The simple JavaScript code present in my ajax page is as follows: <script type=" ...

Issues with Vue Carousel Sliding Functionality

I'm currently tackling a project that involves incorporating Vue Carousel for displaying product slides with both images and text on each slide. My goal is to have only 5 slides displayed per page, complete with navigation arrows and the ability to dr ...

What is the most effective method for transferring resolved promise values to a subsequent "then" chain?

Currently, I am grappling with understanding promises by utilizing the Q module in node.js. However, I have encountered a minor setback. Consider this scenario: ModelA.create(/* params */) .then(function(modelA){ return ModelB.create(/* params */); } ...

The issue of Nodejs Messenger broadcast message functionality being inoperative

Trying to initiate a broadcast through my Facebook Messenger bot, I have implemented the following code: if (subscribe === true) { // Initiate HTTP request to Messenger Platform request({ "uri": "https://graph.facebook.com/v2.11/me/broadcast_messa ...

Modify only the visual appearance of a specific element that incorporates the imported style?

In one of my defined less files, I have the following code: //style.less .ant-modal-close-x { visibility: collapse; } Within a component class, I am using this less file like this: //testclass.tsx import './style.less'; class ReactComp{ re ...

Tips on Calculating the Number of Object Properties and Presenting Each Value Individually on a Dynamic Button with Click Event Attached

When it comes to displaying dynamic data with markers on a map, everything works fine up until this point. However, I've encountered some issues that I'm currently stuck on and not sure how to proceed. Dynamic data: { "page": 2, "data" ...

How can I achieve the same functionality as C# LINQ's GroupBy in Typescript?

Currently, I am working with Angular using Typescript. My situation involves having an array of objects with multiple properties which have been grouped in the server-side code and a duplicate property has been set. The challenge arises when the user updat ...

The custom filter in AngularJS fails to activate when a click event occurs

I am trying to customize the filtering of my table data based on selected conditions from a dropdown menu. I have created an AngularJS custom filter and passed all the necessary parameters. The desired functionality is that if no conditions are selected, ...

Is it possible to eliminate the use of the `this` keyword in a Vue.js application?

I am currently following the guidelines of Douglas Crockford's jslint, which gives a warning when 'this' is used. The warning displayed is: [jslint] Unexpected 'this'. (unexpected_a) I have not been able to find a solution for th ...

Is there a way to determine if jQuery lightslider has been initialized, and if so, how can I effectively remove the instance?

Currently, I have integrated the JQuery lightSlider into my project. Despite some code adjustments, it is functioning well. My goal is to dynamically replace the lightSlider content with data returned via AJAX, which I have successfully achieved. After r ...

Struggling to pass command line arguments to index.ts with yarn?

My objective is to pass arguments through the command line using yarn start to index.ts. "scripts": { "start": "tsc-watch --onSuccess \"ts-node --pretty -r tsconfig-paths/register' src/index.ts\"", } When I attempt something like: yarn ...

Prevent form submission when processing is in progress

I've got this code working perfectly: $(function() { $("input,textarea").jqBootstrapValidation({ preventSubmit: true, submitError: function($form, event, errors) { // additional error messages or events ...