A guide on iterating through a collection of elements in VueJS

I may have approached this project completely wrong from the start, so any advice is greatly appreciated.

My goal is to design a simple webpage with input fields on the right and corresponding hints on the left. When an input field is focused on, the relevant hint should be highlighted on the left side.

You can view a JSFiddle demonstration here: https://jsfiddle.net/eywraw8t/210693/

However, I'm facing an issue in determining how to identify the appropriate hint to highlight (and reset the highlighting for other hints).

I was able to make it work by adding a 'highlighted' property to the field object instead of using a separate hint component. But, since the field data will eventually come from a database without a 'highlighted' parameter, utilizing a hint component seemed like a better option.

In simpler terms, my question is: How can I locate the relevant hint component when an input is focused?

JS Fiddle showing functionality without a component: https://jsfiddle.net/as2vxy79/

Failed JS Fiddle attempt using a component: https://jsfiddle.net/eywraw8t/210693/

Below is the JavaScript code outside of JS Fiddle:

Vue.component('hint', {
    template: `
    <div class="hint" :class="{'highlight-hint': isHighlighted }">
      <slot></slot>
    </div>
  `,
  data() {
    return {
        isHighlighted: false
    }
  }
});

new Vue({
  el: "#app",
  data: {
    fields: [
      {
        'id': 'name',
        'hint': 'Put the name here'
      },
      {
        'id': 'description',
        'hint': 'Put the description here'
      },
      {
        'id': 'more',
        'hint': 'Add more information here'
      }
    ]
  },
  methods: {
    onFocus(focusedField) {
        // Need to loop through the hints somehow
      // Note: There is no "hints" property in this example
      this.hints.forEach(function(field) {
        field.isHighlighted = (focusedField == field.id)
      })
    }
  }
})

Answer №1

In brief: No direct reference to the components displaying the hint is needed as you can utilize reactivity to solve this issue.

All you have to do is include a data field that holds the field id you wish to emphasize and then selectively add a class to the desired hint based on the chosen id (or adjust the component rendering conditionally).

new Vue({
  el: "#app",
  data: {
    highlightedFieldId: '',
    fields: [
      {
        'id': 'name',
        'hint': 'Insert name here'      },
      {
        'id': 'description',
        'hint': 'Add description here'      },
      {
        'id': 'more',
        'hint': 'Include more details here'      }
    ]
  },
  methods: {
    onFocus(focusedFieldId) {
      this.highlightedFieldId = focusedFieldId;
    }
  }
})

Take a look at this updated version on Fiddle.


REMARKS:

  • If there's a necessity for direct references, consider employing the ref directive (this also applies to a list of components created by v-for).
  • Using tooltips for hints might be worthwhile. For example, utilizing Element UI's Tooltip.

UPDATE:

Therefore, I present a solution using the ref directive to access a reference to the highlighted hint component. You'll notice that I incorporated the field id in :ref, yet you will still receive an array from this.$refs[focusedFieldId] due to the surrounding v-for. Apart from that, it's quite straightforward.

I've also enhanced the hint component to accept the is-highlighted prop so it can alter its class independently (previously, you utilized a data property for this which didn't trigger a component update).

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

The ajax call encountered an internal server error while trying to process the $_GET() function

I've been working on a simple login function with jQuery AJAX to save user information in session variables, but I keep running into a 500 error. The PHP file looks like this: <?php session_start(); if (isset($_GET("FirstName"))) { $_SESS ...

Problem with XRController Raycast Range

Having trouble with raycasting in THREEJS using the XR controller when trying to detect objects beyond a distance of 40 units. Raycasting works perfectly within 40 units. Referenced the example in THREEJS: Any suggestions on how to extend the raycasting ...

What is the process for combining AngularJS filters?

I currently have a fragment object like this: [{id: 721, titulo: "Cotizador Gastos Médicos Bx+ 2019", descripcion: "Cotizador Gastos Médicos Bx+ Tarifas 2019", updateDate: "2020-03-25 14:30:22.0", idCategoria: "1", …}, {id: 88, titulo: "Cotizador GMM ...

The error message regarding pdf.worker.min is stating that the use of 'import' and 'export' is limited to within module code and cannot be used outside of it

Upon attempting to deploy a build to Vercel, I encountered the following error message: Failed to compile. static/media/pdf.worker.min.50acc843.mjs from Terser x 'import', and 'export' cannot be used outside of module code ,-[18:1 ...

Steps for applying background color to a chosen element

Using a specific template, I have listed topics in the following way: //Template used for topic list display %li.topic{:topic_slug => "<%=topic.slug%>", :topic_name =>"<%=topic.text%>"} %a{href: "#!/topics/<%=topic.slug%>" } <%= ...

Promise refused due to non-error caution

Error: h1.js:25 Warning: a promise encountered an issue with a non-error: [object String] I am unsure of the root cause of this error and would greatly appreciate any assistance in understanding it. I am currently learning about Promises and AJAX, so any ...

How to access JSON variable containing a point in AngularJS

Currently utilizing Sequelize, I have successfully executed an Inner Join after multiple attempts and achieved satisfying results: { "success": false, "message": "Query not successful, the result was empty", "data": { "codWO": "1016285 ...

Mastering the art of efficiently handling jQuery AJAX in WordPress plugins

Struggling to implement ajax autosave on the settings page of my plugin, I created this code: <?php function cfgeo_settings_javascript() { ?> <script type="text/javascript" > (function($){ $(document).ready(function(){ ...

Utilizing jQuery to load form(s), submit data via POST method, and fetch results without refreshing the

After conducting thorough research, I have been unsuccessful in implementing any of the solutions I have come across. It seems like I am close to a solution, but there may be something crucial that I am missing... A question similar to mine was asked on t ...

Invoke jQuery within a nested context once more in the jQuery method sequence

Is it possible to do something like this? jQuery(selector).jQuery(subselector).command(....) Here is the current code snippet: $(' .species') .filter(function () { return !$(this).data('hidden_code_ready'); } .wrapInner('<spa ...

exploring the possibilities of pairing various data formats using Javascript and Vue

When parsing and mapping two different types of data or objects within i.values, the console output shows: (3) [1, 2, 3,__ob__: Observer] 0:1 1:2 2:3 length:3 __ob__: Observer {value: Array(3), dep: Dep, vmCount: 0} __proto__: Array The next ...

Tips for eliminating default classes from Mui Typography styling

I’ve been working on creating a Typography element and noticed some default MUI CSS classes added when debugging in the browser. I attempted to disable them by using empty arrays at the end of the sx prop, but it did not work as expected. In the image p ...

Having trouble changing fonts in JavaScript Photoshop using scripting on certain fonts

I have created a script for photoshop that is designed to change the font family to a different type. However, I am experiencing some inconsistencies in its performance. Here is the section of the script responsible for altering the font family: var origD ...

Utilizing JQuery to detect a combination of ctrlKey and mouse click event

Looking for assistance with JQuery as I am new to it and still learning the logic. My goal is to determine which index of a textarea was clicked while holding down the CtrlKey. How can I combine an onclick event with a keyboard event and assign a function? ...

Run the function multiple times by substituting a portion of the argument in a sequential

I am facing a challenge with a method (exampleObj.method) that requires arguments of an object and a function. The code snippet is as follows: exampleObj.method({ name1: 'string1', name2: 'string2', name3: &apos ...

Retrieve the unique identifier of the dynamically created button

I have been struggling to retrieve the ID of a dynamically generated button. I attempted to access the specific button ID and utilize it for beforeSend:function(id). However, my efforts were not fruitful. <?php session_start(); require_once "../aut ...

Missing Cookie in request using NodeJS and NextJS

Struggling with integrating cookies in a fullstack app I'm developing using Node for backend and NextJS for frontend on separate servers. The challenge lies in getting the browser to attach the cookie received in the response header from the node serv ...

What is causing the Invalid left-hand side error in the postfix expression at this specific line of code?

I encountered an error stating "invalid left-hand side in postfix expression" while trying to execute this particular line of code data: 'Action=AutionMaxBid&AuctionItemID='+<?php echo $bidItemID ;?>+'', This error occurred d ...

Divs sliding out of alignment

I am experiencing an issue with the scrolling behavior of a wrapper div that contains two nested divs. Specifically, when I scroll the wrapper horizontally on Android devices, the header section and content section seem to be out of sync and there is a not ...

If the JSON value meets the specified condition, the radio button will be selected for display

Displaying Json data: The following JSON data can be altered based on conditions: {"1":"2","2":"2"} I am attempting to set the radio button as checked if the JSON contains a value that matches with the radio button. The first value in the JSON represents ...