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

Emphasize the most recent file during the document upload process and ensure the scroll bar moves accordingly to the document

I am currently working on a feature where the scroll bar should move to the newly uploaded document in a list of documents. When I upload a new document, I want the scroll bar to automatically move to that document. Currently, the highlighting changes to t ...

Exploring the possibilities of jQuery with Accordion functionality and creating dynamic multiple menus

Incorporating the Wayfinder and Accordion menus, I have set up a two-level menu structure for the left column. The structure looks like this: <ul class="accordion">: Menu 1 Sub-menu 1.1 Sub-menu 1.2 Sub-menu 1.3 Menu 2 Sub-menu 2 ...

jQuery load() function triggers unexpected error in jQuery plugin

Here is the current structure of my page: <body> <div id="menuBar"> </div> <canvas id="myCanvas" width="700" height="700" style="border:1px solid #000000;"></canvas> </body> <script src="../Scripts/jQuery.mazeBo ...

What is the best way to manage Page Refresh using Angular.js?

I recently followed the tutorial at http://scotch.io/bar-talk/setting-up-a-mean-stack-single-page-application This guide went over controllers and services using angular.js for a single-page application. However, when I try to directly access /pageName o ...

Ionic: setInterval/setTimer not functioning after 5 minutes in the background

In need of a timer that can send notifications via the OneSignal API after a user-defined time period is reached. Users can set the timer for any value between 1-59 minutes. Despite attempts to use the background mode plugin, specifically setInterval and s ...

Tips for hiding a soft keyboard with jQuery

Here is a text button: <input type="text" class="field" id="something" name="something" placeholder="text" autofocus /> I want to prevent the android soft keyboard from popping up and keep the focus on this field. I only want to do this for this ...

Approach for fetching these JSON records

I am currently exploring ways to retrieve all entries within a JSON payload using JavaScript. Specifically, I am interested in finding the best method to extract all instances of "o4" in a specific order (-159, -257). How can this be achieved? { ...

New from Firefox 89: The afterprint event!

Having an issue with this fragment of code: const afterPrint = () => { this.location.back(); window.removeEventListener('afterprint', afterPrint); }; window.addEventListener('afterprint', afterPrint); window.print(); I&apos ...

"Bower fetches and installs specific versions of packages from the repository

I'm currently using npm 3.3.6 and bower 1.6.8 on Windows 10. Whenever I attempt to install a package like jquery or framework7, it ends up downloading and installing an archived version of the package. Here's an example: > bower install jquer ...

What is the best way to incorporate a range of details into a div using only jQuery, all while avoiding the use of data-

I'm struggling to find a concise way to explain this, so please bear with me. The information I'm sharing here is all just for example purposes and may sound strange. I have been working on creating a character select page where clicking on a cha ...

Look for and choose various fields from a lengthy JSON object

I am working with a JSON object that contains a large list of offerValue objects. { "Code": 0, "response": "SUCCESS", "offerValue": [ { "id": "111", "name": "ABC", "flag": "V" }, { ...

"Troubleshooting a glitch encountered while making an invokeAPI call with Azure Mobile

Working on integrating my Angular App with Azure Services as the back end. Initially, I used the standard $http call: $http({ method: 'POST', url: "https://services.example.com/Api/myApi", headers : { "Content-Type" ...

What is the best approach to create a dynamic value from axios response in a reactive object?

I am attempting to retrieve data from the backend (specifically the user role) and store it in a reactive container with Vue: import {reactive} from "vue"; import axios from "axios"; export const store = reactive({ auth: axios.get ...

The font size of the textarea dynamically adjusts based on the size of the screen

Some strange behavior is occurring in the Android default browser when I set the width and height of a textarea to 100%. The font size of the textarea seems to increase based on the screen size, and even though I attempted to alert the font-size using jQue ...

loading dynamic content into an appended div in HTML using Angular

Here is the HTML code from my app.component.html file: <button mat-raised-button color="primary" mat-button class="nextButton" (click)="calculatePremium()"> Calculate </button> <div id="calcul ...

Get rid of the folder from the URL using an <a> tag

I have both an English and French version of my website located at: *website.com/fr/index.php *website.com/index.php Currently, I have a direct link to switch between the two versions: -website.com/fr/index.php -website.com/index.php. However, I ...

Trouble with Background Image Display in Internet Explorer 8

I have been attempting to set a background image for the . element, but it is not displaying correctly. The image shows up in Firefox and Chrome, but not in Internet Explorer. I have included a link to my website and relevant CSS code below. Can anyone pro ...

Changing the Div heights in Material UI with grid layout customization

I have a project that requires me to implement material-ui. Is there a way I can adjust the width and height of the div containing the "Sign In With" text (as shown in the first image) to bring the buttons closer to the text? Transformation from this: ht ...

Creating a custom table layout with JavaScript and jQuery

I've been grappling with a project for some time now, and I'm stuck on this particular issue. In my database, I have a table structured like this: ProjectName UserName SpentDays FirstProject User1 10 SecondProject User1 5 SecondProjec ...

Using sl-vue-tree with vue-cli3.1 on internet explorer 11

Hello, I am a Japanese individual and my proficiency in English is lacking, so please bear with me. Currently, I am using vue-cli3.1 and I am looking to incorporate the sl-vue-tree module into my project for compatibility with ie11. The documentation menti ...