Exploring the vueJS canvas life cycle and transitioning between components

Struggling with displaying Vue components that contain a canvas with different behaviors.

Looking to switch components using v-if and passing different properties.

Here's a small example:

Currently, when switching from 'blue' to 'red', the color remains 'red' in the drawing even though the DOM shows the switch to 'canvas2.'

--- COMPONENT ---

<template>
    <div class="container-fluid">

        <canvas style="border: 1px solid black;" width="300px" height="150px" :id="'canvas'+canvasKey"></canvas>

    </div>
</template>

export default {
    data: function() {
        return {}
    },
    mounted: function() {
        this.draw_canvas();
    },
    created: function() {},
    watch: {},
    props: ['canvasKey'],
    computed: {},
    methods: {
        draw_canvas: function() {
            var app = this;
            var c = document.getElementById("canvas"+this.canvasKey);
            var ctx = c.getContext("2d");

            if(this.canvasKey == 1) {
                var color = 'red';
            } else if(this.canvasKey == 2) {
                var color = 'blue';
            }

            var mousePos = function(mouseEv) {
                let offset = $("#canvas"+app.canvasKey).offset();
                let pos = {
                    x: mouseEv.pageX - offset.left,
                    y: mouseEv.pageY - offset.top,
                };
                return pos;
            }

            $('#canvas'+this.canvasKey).on('mousemove' , function(ev) {
                var pos = mousePos(ev);
                ctx.beginPath();
                ctx.arc(pos.x, pos.y, 10, 0, 2 * Math.PI);
                ctx.fillStyle = color;
                ctx.fill();
            });
        }
    }
}

--- CREATE COMPONENT ---

<canvas-test v-if="color == 'red'"  canvasKey="1"></canvastest>
<canvas-test v-if="color == 'blue'" canvasKey="2"></canvas-test>

I hope my question is clear. Any assistance would be greatly appreciated. Thank you in advance!

Answer №1

Avoid using a non-reactive variable within v-if statements as it is not supported. This results in the v-if evaluation remaining constant, even when the variable color changes, leading to the same component being rendered consistently.

To resolve this issue, consider utilizing a color data property in the parent component and apply v-model or v-bind:value to handle it effectively (as outlined in Using-v-model-on-Components in the documentation). Within the parent component:

<template>
  ...
    <canvas-test v-if="color == 'red'" v-model="color"  canvasKey="1"></canvastest>
    <canvas-test v-if="color == 'blue'" v-model="color" canvasKey="2"></canvas-test>
  ...
</template>
<script>
...
export default {
  data () {
    ...
    color: 'red',
    ...
  }
  ...
  components: {
    CanvasTest
  }
  ...
}
</script>

within the canvas component:

<script>
...
export default {
  ...
  props: ['value'],  // the color is in 'value'
  ...
}
</script>

If your intention is to have multiple components with distinct properties, define these properties using props.

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

What is the reason behind "Script" being considered the offspring of "Body"?

Unfortunately, I struggle with HTML/CSS/Javascript and am just trying to get through my exams. I have the code snippet below: <script> window.onload=function() { var c = document.body.childNodes; var txt = ""; var i; for ...

The term 'Word' is not recognized within the office.js Add-in when used with Word 2013

I'm currently developing an Office.js Add-in for Word, and it's working seamlessly in MS Word (Windows 10, 1909 & Office 18.2005.1191.0 - meaning the add-in runs in the Edge browser) as well as in the browser on office.com (IE11, Chrome, Edge ...

Activate the Sass IntelliSense feature specifically for .vue files within the VS Code editor

Could IntelliSense for Sass be activated in .vue documents without connecting them to sass, as this may disrupt other extensions dependent on the .vue file association? ...

How to use jQuery to gather all the text from a textarea

Is there a way to automatically select all text inside a textarea when it is clicked on? Additionally, can this selection be deselected by clicking again? ...

What is the reason that setTimeout does not delay calling a function?

I am looking to develop a straightforward game where a div is duplicated recursively after a short interval. Each new div should have a unique ID (ID+i). The concept is to continuously generate divs that the user must click on to remove before reaching a ...

Navigating between routes in NEXT JS involves passing state, which can be achieved through various

Within one of my page objects, I have some data that I need to send to another page when redirecting. The code snippet below shows how I achieved this: const redirectAppointmentStep1 = (value) => { router.push({ pathname: '/Appointment/bo ...

What is the best way to display a 404 error page for a nonexistent child page on a WordPress site?

After building our site with WordPress, I noticed that non-existent child page routes are not being redirected. For instance, let's say we have a page called about-us with the URL http://example.com/about-us. If I try to access a non-existing child p ...

The authentication0 router fails to initiate navigation

I'm currently using Auth0 in combination with Angular 2. The issue I am encountering is that my login code isn't redirecting to the home page after authentication. Based on my understanding, Auth0 does not handle the redirection process itself. ...

Attempting to monitor the frequency of calls to a JavaScript function

let totalEnteredCount = 0; function totalEntered(field){ if(field.value != '') { totalEnteredCount++; } alert(Counter); if(totalEnteredCount == 3) { var InitialVelocity = document.getElementById("IVUnit").value; var FinalVelocity = do ...

Code for Custom Controllers in Strapi Beta version 3.0

I have encountered some discrepancies in the beta version of Strapi's controllers compared to the previous version. The new version includes multipart/sanitization boilerplate, and I am having trouble integrating my order object and Stripe charge. Be ...

Steps for updating a value in a JSON file using PHP

Trying to modify a value within a JSON file for a specific object is throwing me off balance. The issue arises from having multiple siblings in the same JSON file sharing identical key-value pairs. The JSON structure I'm dealing with appears as follo ...

Exploring the art of manipulating HTML code using JavaScript

I am looking to implement a specific change using JavaScript: <input id="innn" value="" /> to: <input id="innn" value="SOME_VALUE" /> I attempted the following methods: document.getElementById("innn").setAttribute("value", "189"); and als ...

"Enhance user experience with the React Popover feature from Material UI

Looking for help on creating a dynamic color palette with a hover feature for the PaletteIcon. The issue I'm facing is that when I try to select a color, the palette disappears. Is there a specific property I should add to the React component or anoth ...

"Problems arise with mongodb full $text search when sorting and filtering, causing duplicate items to

When using full-text search in my API and sorting by score, I am encountering an issue where the same item is returned multiple times. This behavior is not what I expected. How can I correct this to ensure unique results? Below is the structure of my rout ...

What is the process for renaming a Discord channel through nodeJS and discordJS?

I'm currently developing my first Discord bot using node.js and discord.js. My objective is to provide real-time information about a Minecraft server through Discord. What I aim to achieve is to have a channel that automatically updates its name per ...

how to execute Vue-Js method just one time

Is there a way to add a random number (ranging from 0 to the price of an item) to one of the data properties in Vue.js, but only once when the page is initially loaded? I am unable to use mounted and computed because I need to pass a parameter to the funct ...

In Laravel, Inertia.js will automatically close a modal if there are no validation errors present

Here is the method I am currently using: methods: { submit() { this.$inertia.post('/projects', this.form); this.openModal = false; }, }, Unfortunately, this method closes the modal even if there are validation erro ...

The X axis labels are missing on the Google column chart

Problem: All column charts are rendering correctly in Internet Explorer. However, Upon clicking the "View Build Performances" button, project names are displayed on the x-axis of the first three column charts only. The other column charts do not show pro ...

A-Frame VR: Image missing from display on Chrome browser

UPDATE: I discovered that the issue was caused by running the HTML file from my local hard drive instead of a web server. Once I uploaded it to my web server and ran it from there, everything worked perfectly. A-Frame Version: 0.4.0, Chrome: 55.0.2883.87, ...

Toggle a jQuery bar based on the presence of a specific CSS class

I am working on a feature where I can select and deselect images by clicking on a delete button. When an image is selected, a bar appears at the top. If I click the same delete button again, the image should be deselected and the bar should disappear. This ...