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

Working with Vue/Nuxt to loop through a collection of documents in Firestore using v-for

This is my first project using Vue and Firebase. I am working with NuxtJS (Vue v2.x) along with Vuetify and Firestore. My goal is to iterate through a collection of documents and display Vuetify Card components with the relevant data. Currently, all the ...

Is it possible to send a PHP variable to a popup using a button and JavaScript?

I am facing an issue with a dynamically created table in PHP that displays requests. Each row in the table has a button to open a popup. I need to pass the ID of each request to the popup to retrieve all the data associated with it. Can someone guide me o ...

javascript creating unique model instances with mongoose

I've searched through related posts without finding exactly what I need. Currently, I am working on building a backend rest API and conducting tests to collect data. Each test has its own model which is associated with collections in the database. T ...

The table row disappears but the value persists

I have designed a table where users can perform calculations. However, when a row is deleted, the values from that row appear in the row below it and subsequent rows as well. What I want is for the user to be able to completely remove a row with its values ...

Utilizing form data to upload images and send them back to the front end within a React js application

I am working on a project using NestJS and React JS to create an image uploader. In React, I have the following setup: const props = { onChange({ file, fileList }: any) { const fd = new FormData(); fd.append('img& ...

Having trouble getting my Leaflet map to display even after meticulously following the quick-start guide

I am experiencing an issue where the map is not displaying at all, leaving a blank space where it should be. Despite following Leaflet's quick-start guide, I have been unable to determine the cause of this problem. Here is the code that I currently h ...

How can I ensure that my text input and button are in sync in ReactJS?

I'm currently developing a basic search bar that reads input and updates the 'inputString' state when the content changes. Upon clicking the 'search' button, the inputString is split and assigned to the 'keywords' state a ...

When there is an absence of data, the jQuery datatable mysteriously van

I have encountered an issue in my Django app where a datatable used in the template disappears if there is missing data in any column or row. The problem occurs when trying to download the data in CSV, Excel, PDF, or copy format. Here is the HTML code snip ...

Utilizing the Filter Function to Eliminate an Element from an Array

I am a beginner in the world of React and I'm currently working on developing a simple timesheet tool where users can add tasks and save them. My tech stack includes React and Typescript. Currently, my main component has an empty array for tasks and ...

AngularJS enables the loading of directives dynamically, but sometimes encounters errors such as "Restricted URI access denied."

Presently, I am in the process of developing a small educational project using HTML5, CSS, JS and AngularJS. Hiccup: Loading an AngularJS Directive in my index.html file Error code [1] - Local browser Error: Access to restricted URI denied Various resp ...

Issue with custom leaflet divIcon not maintaining fixed marker position during zoom levels

After creating a custom marker for leaflet maps, I noticed that it shifts position drastically when zooming in and out of the map. Despite trying to adjust anchor points and positions, the issue persists. I have provided the code below in hopes that someon ...

Issues with returning undefined values in JSON with Node.js and AngularJS

I have developed an application that communicates with an API to retrieve and display data. The process involves entering a username in the client input, which is then sent to the server. Upon checking, everything seems to be working fine at this stage. H ...

Altering the appearance of an input field upon submission

https://jsfiddle.net/3vz45os8/7/ I'm working on a JSFiddle where I am trying to change the background color of input text based on whether the word is typed correctly or incorrectly. Currently, it's not functioning as expected and there are no e ...

Getting Started with Cloudinary Image Upload using Nuxt.js

I'm currently facing an issue while attempting to upload an image to cloudinary from the client side. Even though I have created a Form Data and tried to pass it, it seems to be coming back empty. Here is the HTML code snippet: <div class="my ...

Node js does not support iteration for DirectoryFiles

I am currently working on a program aimed at mapping all the json files within a specific directory. As I am new to JavaScript, this inquiry may not be ideal or obvious. Here is my code: const fs = require('fs'); const { glob } = require('gl ...

Tips for integrating Material UI Drawer with Redux

I have been attempting to incorporate a Drawer feature that displays on the left side while utilizing Redux to maintain the state of the Drawer. Unfortunately, I seem to have made an error as my onClick events are not responsive. Here is the code: Reduce ...

Excessive Function Calls Detected in AngularJS Application

I'm facing a major performance issue. I need to display details in a list, but the function is being called excessively. Feel free to check out the demo here Here's the HTML code snippet : <div ng-controller="MyCtrl as ctrl"> <p>K ...

Manipulating the "placeholder" attribute with Knockout.js and JSON data

Is it possible to use the placeholder attribute with data-bind? I am encountering an error message ([object object]). Can someone help me figure out how to properly utilize it? html: input id="comments" class="form-control" data-bind="attr: { placeholde ...

Navigating a JSON object using jQuery

My current project involves sending a Json response to an Ajax function within my webpage. The structure of the Json response is as follows: {"one": 21, "two": 10, "three": 19, "four": 100} With this setup in place, I am now in the process of developing ...

Generate a div element dynamically when an option is selected using AngularJS

I'm having trouble dynamically creating div elements based on the selected option value, but for some reason ng-repeat isn't working as expected. Can you help me figure out what I'm missing? Here's the HTML snippet I'm using - &l ...