What is the best way to execute a function individually for every tag within a vue.js application?

I'm currently exploring the world of Vue JS and I thought it would be interesting to experiment with something new. Sometimes looking at the code first makes understanding it much easier than a lengthy explanation.

Check out this code snippet on jsFiddle!

In the code, you will notice two placeholders ([% message %]). My goal is to display a random color for each of these placeholders from a predefined list. Do you think this is achievable?

Here's the HTML structure:

<div id="app-5">

  <div class="color">
    <span class="colorHandler">
      <p>[% message %]</p>
    </span>
  </div>

  <div class="color">
    <span class="colorHandler">
      <p>[% message %]</p>
    </span>
  </div>

  ... # the quantity of these specific '[% message %]' tags may vary.
</div>

This is the JavaScript (VueJs) part :

var colors = "['#e6f0ff', '#000a1a' ,'#ffe680', '#ffcc00', '#ffd9b3']";
var parsed_colors = colors.match(/#[a-f0-9]{6}/g);
var randomIndex = Math.floor(Math.random() * parsed_colors.length); 
var randomElement = parsed_colors[randomIndex];

var app5 = new Vue({
  el: '#app-5',
  data: {
    message: randomElement
  },
  delimiters: ["[%","%]"]
})

Any thoughts on how I can make this work? Your guidance would be greatly appreciated!

Answer №1

Check out this link for using methods in Vue.js (don't forget to refresh the page as values may sometimes be the same).

var app5 = new Vue({
  el: '#app-5',
  data: {
    message: null
  },
  methods:{
    randomColor:function(){
        var colors = "['#e6f0ff', '#000a1a' ,'#ffe680', '#ffcc00', '#ffd9b3']";
      var parsed_colors = colors.match(/#[a-f0-9]{6}/g);
      var randomIndex = Math.floor(Math.random() * parsed_colors.length); 
      var randomElement = parsed_colors[randomIndex];
      return randomElement
    }
  },
  delimiters: ["[%","%]"]
})

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

Initiate a jQuery modal dialogue box

As an apprentice with no prior experience working with JavaScript, I encountered a problem with my function that calls a popup. The function works fine on the first button, but fails to work on all subsequent buttons. Since the application keeps adding b ...

"The variables in the .env file are not reflecting the latest updates. What is the best way

Currently, I am in the process of developing an application using Quasar (Vue) where I have stored my database keys in a .env file. Recently, I encountered an issue when attempting to switch to another instance and updating the keys in the env file. Despit ...

Select2.js Dropdown List with Case Sensitivity

Currently making use of select2.js version 4.0.3 Situation: Imagine the dropdown list contains the following options: JavaScript javascript Javascript javaScript So, when a user types in java, all options are displayed (case is n ...

What happens when arithmetic operators are applied to infinity values in JavaScript?

Why do Arithmetic Operators Behave Differently with Infinity in JavaScript? console.log(1.7976931348623157E+10308 + 1.7976931348623157E+10308)//Infinity console.log(1.7976931348623157E+10308 * 1.7976931348623157E+10308)//Infinity console.log(1.797693134 ...

What is the most effective way to stop zooming when focusing on form fields on iOS or similar devices when using font sizes of 16px or lower?

It appears that many proposed solutions involve changing the text to 16px or using JavaScript to determine if the phone is an iPhone. However, altering the style may not be the most practical solution and checking for specific devices like iPhones could ...

Differentiate various collections of shapes

My application has a specific workflow: 1) Next to the name of Patient X, there is a "Check In" button. Once clicked, this action is recorded on the server side. 2) Upon clicking the "Check In" button, a dropdown menu appears with various locations for t ...

What is the method to view all components within a Vue project displayed in a tree format?

In my extensive Vue 2 project, I have numerous nested components that are used in several places. I am searching for a Visual Studio Code extension that can display a graphical representation of which components are utilized where. Instead of manually lo ...

Customized link routing / Deep linking

I need some help. I am managing a standard website and I want to redirect custom URLs to specific pages when visitors access the site. For instance: - index.html should point to custom_index.cfm?custom_id=1&page_id=1&inc=index - about.html shou ...

What is the technique for adjusting the background while rotating the corner?

Is it possible to position a background image in the corner while rotating another image? rotate: $('#ship').css({ transform: 'rotate(' + corner + 'deg)' }); } move background: starx[i]=starx[i]+... s ...

The data in ag Grid does not display until all grid events have been completed

After setting the rowData in the onGridReady function, I noticed that the data does not display until all events are completed. I also attempted using the firstCellrendered event, but unfortunately, it did not resolve the issue. OnGridReady(){ this.r ...

Issue arising with data exchange between components using data service in Angular 5

Utilizing data service to share information between components has presented a challenge for me. References: Angular: Updating UI from child component to parent component Methods for Sharing Data Between Angular Components Despite attempting the logic o ...

Utilizing a function from a library in an Object within a Typescript environment

Currently, I am working on assigning a field within my interface to a function from an external library in the following manner: import { Accelerometer, } from 'expo-sensors'; type SensorInterface = { permChecker: () => Promise<Permiss ...

Warning: Promise rejection was not handled (rejection id: 3)

As a newcomer to the world of await, I'm struggling to handle errors and rejections properly. The unhandled rejections from the shopify-api.js function keep cropping up, and I can't seem to print all the errors that are coming from my middleware ...

Express server consistently receives JSON requests that contain no data in the request body

Currently, I am in the process of developing a small server and website using Express. At this point, my goal is to send a POST request to my Express server with basic credentials encoded as JSON. The issue I am facing is that no matter what I attempt, th ...

What is the best way to determine if a property exclusively belongs to the child class or its subclass in Javascript?

I am currently working on a project in Javascript where I need to retrieve properties that are only present in a subclass (child class) and not in the parent class. Despite using .hasOwnProperty(), I have run into an issue where it also returns true for th ...

What is the best way to ensure a multi-page form is validated using HTML5 and JavaScript before progressing to the next page?

Currently, there are two functionalities at play. The submit button is not being recognized while the functionality in JS $(".next").click(function(){..} is working as expected. HTML This section involves 4 fieldsets. I am attempting to validate ...

Mastering the placement of script tags in your Next.js application with Next Script

I'm in the process of integrating a third-party script into my Next.js website. This particular script adds an iframe right below its corresponding script tag. Therefore, it is crucial for me to have precise control over the placement of the script ta ...

Is it possible to capture a submit event from a form within an iframe using jQuery or JavaScript

If I have a webpage with an embedded iframe containing a form, how can I update a hidden field value on the main page once the form is submitted? What is the best way to trigger an event in the parent page upon form submission? Here's a simplified ex ...

Prevent mouse over scrolling for every <select> element on a webpage using JQuery

My code seems to be having some issues. Can you help me figure out what's wrong? <script type="text/javascript" language="javascript"> //trying to disable scrolling on mouse over of <select> elements $(document).ready(function() { ...

Mapping in React/Javascript: How to Efficiently Return Multiple Items

How can I efficiently return multiple outputs in a .map function, such as two separate console.log statements? For instance, the following code works: return ( <div className="App"> {mycataobjects.map((myobject) => console.lo ...