Accessing a variable from one function within another function in Vue

How can I access and utilize the ctx variable from the initGrid() function in the drawGrid() function? Despite trying to use "this," it seems that the variable cannot be accessed within the drawGrid() function.

<script>
export default {
  data: () => ({
    width: 1200,
    height: 800,
    squareH: 15,
    squareW: 15,
    squareRow: 10,
    squareCol: 10,
    squares: [],  
  }),
  
  directives: {},
  methods: {
    initGrid() {
      let grid = document.getElementById('grid');
      
      var ctx = grid.getContext('2d');
      
    },
    drawGrid() {
      this.ctx.fillStyle = 'black';
      this.ctx.fillRect(10, 10, this.squareW, this.squareH); 
    }
  },
  mounted() {
    this.initGrid();
    this.drawGrid();
    
  }

Answer №1

Simply include it in the data object and utilize it within both functions:

<script>
export default {
  data: () => ({
    width: 1200,
    height: 800,
    squareH: 15,
    squareW: 15,
    squareRow: 10,
    squareCol: 10,
    squares: [],  
    ctx:null
  }),

  directives: {},
  methods: {
    initGrid() {
      let grid = document.getElementById('grid');

     this.ctx = grid.getContext('2d');

    },
    drawGrid() {
      this.ctx.fillStyle = 'black';
      this.ctx.fillRect(10, 10, this.squareW, this.squareH); 
    }
  },
  mounted() {
    this.initGrid();
    this.drawGrid();

  }

Answer №2

To ensure the component has access to the data, it is necessary to establish a connection. Simply calling var ctx = grid.getContext('2d'); within the init grid function creates the grid and ctx variables, but does not explicitly inform vue or the component that they should be associated with the state. The solution lies in initializing the component's data with the ctx information.

<script>
export default {
  data: () => ({
    width: 1200,
    height: 800,
    squareH: 15,
    squareW: 15,
    squareRow: 10,
    squareCol: 10,
    squares: [],
    ctx: null, 
    // Include ctx in the data initialization.
  }),
  
  directives: {},
  methods: {
    initGrid() {
      let grid = document.getElementById('grid');
      
      // Now this.ctx is defined and ready for use
       this.ctx = grid.getContext('2d');
      
    },
    drawGrid() {
      this.ctx.fillStyle = 'black';
      this.ctx.fillRect(10, 10, this.squareW, this.squareH); 
    }
  },
  mounted() {
    this.initGrid();
    this.drawGrid();
    
  }

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

Leveraging jQuery within a webpack module shared across multiple components, located outside the webpack root directory

When working with multiple layouts that rely on shared typescript files, it is important to ensure these files are accessible across different layouts using webpack. While attempting to include jquery in my ajax.ts, I encountered the following error: ERR ...

How can you create a basic click event for a Google Maps marker?

Can a straightforward action be triggered using jQuery or JavaScript when a user clicks on a Google Maps marker? I am attempting to load content into an external div using AJAX when a user clicks on a marker on the map. The following code snippet could se ...

Progressive Web App with Vue.js and WordPress Rest API integration

When creating an ecommerce website using Wordpress, I utilized Python for scraping data from other websites to compare prices and bulk upload products through a CSV file. My next goal is to learn Vue and transform the website into a PWA as it will be esse ...

ES6 allows for the retrieval of method data within an object

My goal is to improve the organization of my code by creating a config file where I can use the same method to set values. This is just a demonstration, so please keep that in mind. I'm wondering if there's a way to call a function based on wheth ...

Tips for optimizing the performance of nested for loops

I wrote a for loop that iterates over 2 enums, sending them both to the server, receiving a value in return, and then calculating another value using a nested for loop. I believe there is room for improvement in this code snippet: const paths = []; for awa ...

Function that can be shared between two separate jQuery files

Let's say I have two separate jQuery files, both containing the same function. I would like to create a common file where I can store this shared function and then import it into other files. For example: first.js file : window.addEventListener(&apo ...

Having trouble parsing the JSON object values within the Error section of the Ajax call

When making an Ajax call to a rest web API, I encountered an error that I need help resolving. Here is the code snippet: $.ajax({ url: "/********/getbytitle('****')/items", type: "POST", contentType: "applicat ...

Utilizing jQuery for AJAX requests on a timed loop

I'm puzzled by a situation involving an AJAX call within an interval. It seems that the code doesn't work as expected, and I'm wondering why. Initially, I had this code snippet which wasn't functioning properly: setInterval($.ajax({ ...

How can Selenium interact with various shadow DOM elements within a dropdown menu?

I am attempting to interact with a dropdown menu in order to track activity on the page when clicking on one of its items. Here is an overview of my HTML structure: <slot> #shadowroot <myoption-cmp> #shadowroot <some anchor te ...

Use angular js to dynamically load a template via an ajax request

I am trying to send an AJAX request in order to retrieve a JSP/HTML page for the templateUrl of a modal. Here is the code I have written: var modalInstance = $uibModal.open({ animation: $scope.animationsEnabled, te ...

What could be causing the script to not function properly on 3D text in Unity5?

Here is the code snippet I have been working on: function OnMouseEnter() { GetComponent(Renderer).material.color = Color.grey; } function OnMouseExit() { GetComponent(Renderer).material.color = Color.white; } I've noticed that when I apply t ...

ES6/JS: Locate a specific text within a nested object and return a true value

I need help filtering a vuetify data-table. You can find the codepen link here: https://codepen.io/rasenkantenstein/pen/MWYEvzK. I have a filter with the string "Ice", and I want to retrieve all records that contain an ingredient with "ice" in its name. [ ...

Getting a blank request body error while receiving data from an Angular 4 application in Express

My express route is indicating that the body of the request being sent is empty, according to req.body. The main node file looks like this - var express = require('express'); var bluebird = require('bluebird') const bodyParser = requ ...

Converting JS carousel to TS for showcasing multiple items

I am currently working on integrating a bootstrap carousel into my Angular project and I need to convert my JavaScript file to a TypeScript file. As someone who is new to this, I'm unsure of the process for converting and implementing it in a .ts file ...

How can I automatically assign a default local image if the image source in the JSON response is empty?

I am currently developing a Chrome extension where I want to display both images and text in the popup window. Everything seems to be working fine, however, when the JSON data for the image src is empty, I'm struggling to set a default image. Despite ...

Tips on accessing the local storage token within the Vue methods attribute

I am facing an issue with my Vue app that requires a token when sending a request. Every time I try to send a request, I keep getting an error saying "token not defined." Here is the error message: https://i.sstatic.net/Sxxdz.jpg This is how I call my me ...

Manipulating data in node.js as it arrives in separate chunks

Hey there, I am trying to make some changes to the data received from the server. All incoming data via the POST method is processed in chunks. <button id='helloButton'>Send hello!</button> <button id='whatsUpButton'>S ...

Indeed, verifying parent.parent access

Currently, I am utilizing the yup module to validate my form. My objective is to access the parent in order to test the value. Below is my schema: enabled: yup.boolean(), contactDetail: yup.object().shape({ phoneNumber1: yup.string().nullable(), pho ...

You do not have permission to access the restricted URI, error code: 1012

What is the best solution for resolving the Ajax cross site scripting issue in FireFox 3? ...

Set up an event listener for when geolocation permission is approved

My Setup: I've written some basic code snippet below: const onSuccess = () => { console.log('success'); } const onError = () => { console.log('error'); } navigator.geolocation.getCurrentPosition(onSuccess, onError) ...