Numerous references embedded within a Vue.js component

I am currently working with multiple instances of a polygonCrop component in Vue.js, each one having a unique reference to a canvas property. These components are utilized in separate crop functions triggered by button clicks. My question is how to effectively use multiple refs with multiple components in Vue.js?

<polygonCrop 
    :canvasClass="'some-class'"
    :height="600"
    :imageSource="imgSrc"
    :showCanvas="show"
    :showPointer="showPointer"
    :width="800"
    ref="canvas"
></polygonCrop>
<polygonCrop 
    :canvasClass="'some-class'"
    :height="600"
    :imageSource="imgSrc1"
    :showCanvas="show"
    :showPointer="showPointer"
    :width="800"
    ref="canvas1"
></polygonCrop>
...
<b-button @click.prevent="crop" variant="success">Crop</b-button>
<b-button @click.prevent="crop1" variant="success">Crop</b-button>
...
crop: function () {
    this.$refs.canvas.crop();
    this.resultImage = this.$refs.canvas.resultImage;
    this.show = false;
    this.showResult = true;
},
crop1: function () {
    this.$refs.canvas1.crop();
    this.resultImage1 = this.$refs.canvas1.resultImage;
    this.show = false;
    this.showResult = true;
},

Although I am utilizing multiple canvases with references like canvas and canvas1, I'm unsure if this is the correct approach. Any guidance on this matter would be greatly appreciated.

Answer №1

If you have multiple elements with unique props for each element, it is not recommended to use this approach. Instead, consider creating an array containing multiple objects, with each object including the necessary data for that canvas. For example:

data(){
  return {
      canvases:[
        {
          class: 'class-name',
          imgSrc: 'image-source',
          width: 800,
          height: 600,
          ....
        },
        {
          class: 'class-name-2',
          imgSrc: 'image-source-2',
          width: 800,
          height: 600,
        }
         ....
      ]
  }
}

You can then loop through this array:

<!-- 5 elements -->
<polygonCrop 
             v-for="(canvas, i) in canvases"
             :key="i"
             :canvasClass="canvas.class"
             :height="canvas.height"
             :imageSource="canvas.imgSrc"
             :showCanvas="show(i)"
             :showPointer="showPointer"
             :width="800"
             :ref="'canvas-' + i"
></polygonCrop>

If you prefer to keep your current code structure, here is a solution for you

For the DOM, utilize a v-for loop with dynamic ref binding, and for the image sources, use a method to match the variables' names:

<!-- 5 elements -->
<polygonCrop :canvasClass="'some-class'"
             :height="600"
             :imageSource="getSource('imgSrc' + n)"
             :showCanvas="show"
             :showPointer="showPointer"
             :width="800"
             v-for="n in 5"
             :key="n"
             :ref="'canvas-' + n"
></polygonCrop>
<b-button @click.prevent="crop(n)" variant="success" v-for="n in 5">Crop {{n}}</b-button>

Utilize only one crop function, accepting a parameter:

// methods
crop: function (n) {
    const canvas = 'canvas-' + n 
    this.$refs[canvas].crop();
    this.resultImage = this.$refs[canvas].resultImage;
    this.show = false;
    this.showResult = true;
},
getSource : function(img) {
  return this[img]
}

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

jQuery if statement appears to be malfunctioning

When the condition operates alone, everything works fine. However, when I introduce an 'and' operation, it does not function correctly. If only one of them is true, the code works. It also successfully takes input values. <!DOCTYPE HTML Code ...

Having trouble with the installation of Vue CLI

Can you please explain the meaning of this? What steps should I take with regards to this issue while setting up vue? Is it a common occurrence or something that needs special attention? > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

communicating data within a JavaScript file across server and client

One of my files, parameters.js, contains the following JavaScript code: const myJSON = { parameter1: 2, parameter2: 2. } module.exports = {myJSON} In another file called server.js, I can access this data by usin ...

Encountering a value accessor error when attempting to test a simple form in Angular 4 and Ionic 3

My ionic form is quite simple: <ion-header> <ion-navbar> <ion-title>Foo</ion-title> </ion-navbar> </ion-header> <ion-content padding> <form [formGroup]="fooForm"> <ion-item> ...

Vue.js - Communicating attribute names with a Child component

Currently, I am in the process of developing a Vue SelectComponent. One of the requirements I have is to pass the name of the Select as an attribute to the component like this: <select-component selectName="providers"></select-component> With ...

Progressing in a connected sequence of changes on a linear graph with distinct points and a pause

A jsfiddle has been created here. Looking to move a circle along a sine wave graph, triggered by a click event. The circle should stop at specific x and y value pairs on the graph before moving to the last point and looping back to the first (ideally unti ...

Knockout Mapping is causing a complete re-render of all elements

Utilizing the Knockout mapping plug-in to update the UI with JSON data fetched from the server every 3 seconds. The UI contains nested foreach bindings. However, it appears that all elements within the foreach bindings are completely erased and re-rendered ...

The Node.js application gracefully exited with code 0 with Forever

Running a Node.js Express app on CentOs 6.5 using the root account: root@vps [/home/test/node]# npm start app.js > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aedacbdddaee9e809e809f">[email protected]</a> s ...

Having trouble retrieving exchange rates from the state in React after making an API call

import React, { Component } from 'react'; import axios from 'axios'; class SearchCurrency extends Component { constructor() { super(); this.state = { data: {} } } componentDidMount() { axios .get(&apo ...

What's the simplest method for updating a single value within a nested JSON object using TypeScript?

Using TypeScript version ^3.5.3 Consider the following JSON data: const config = { id: 1, title: "A good day", body: "Very detailed stories" publishedAt: "2021-01-20 12:21:12" } To update the title using spread synta ...

Creating JavaScript objects through function calls

let getBoxWidth = function() { this.width=2; }; alert(getBoxWidth.width); Hello there! Can you explain why the output is undefined in this scenario? ...

Exploring the power of Vue.js with the versatile v-for

I'm new to vue.js and I'm looking to retrieve data from app.js using v-for in HTML to display it in separate divs. I want each todo item to have its own background and text. var example = new Vue({ el:"#example", data: { todos ...

Tips for storing Vue3 OpenLayers coordinates in Django with SRID4326

Creating markers in OpenStreetMap is my current project. I have a building in Bangkok and when I use Django, the coordinates displayed are: "SRID=4326;MULTIPOINT (100.53007692708017 13.721325314629256)" I decided to create markers using Vue3. He ...

I encountered a data discrepancy while attempting to link up with a weather API

This is my debut app venture utilizing node.js and express for the first time. The concept behind this basic application involves connecting to an external API to retrieve temperature data, while also allowing users to input their zip code and feelings whi ...

The inline style fails to take effect on input elements that are generated dynamically

Consider: $( "#scanInDialogItems tr td:nth-child( 3 )").mouseenter( function() { var q = $( this ).html(); $( this ).html( "<input type='number' style='text-align:right width:50px' min='1' value='" + q + " ...

Experiencing difficulties loading Expo Vector Icons in Nextjs

I've spent countless hours trying various methods to accomplish this task, but unfortunately, I have had no luck so far. My goal is to utilize the Solito Nativebase Universal Typescript repository for this purpose: https://github.com/GeekyAnts/nativ ...

Issue: Elements within an iteration must include a 'v-bind:key' directive. Vue/Require-v-for-key error detected

As someone who is just starting to learn Vue, I recently attempted to create a commercial product page by following a tutorial. However, upon trying to run 'npm run serve', I encountered an error that read: Error: Elements in iteration expect to ...

"jquery-ajax was unable to complete the request, whereas it was successfully executed using

I am currently using jQuery to trigger an ajax request. However, when I make the request using jQuery, I encounter an "Unexpected end of input" error with no response coming from the PHP file. Strangely enough, if I manually copy the request from the Chrom ...

Laravel Mix Hot Module Replacement (HMR) failing to update after compilation

My current Laravel Mix version is 4.0.13. When I use npm run watch, everything works smoothly, and even when I run npm run hot, it seems to compile and detect my changes, recompiling as needed. However, despite these actions in the console, there is no v ...

Ways to provide information to an rxjs observer

It appears that most people find observers to be a piece of cake, but I personally struggle with them. I am trying to set up an observable that can receive a number input after it has been created, triggered by pressing a button. However, all the examples ...