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

Exploring the world of Django: Using model formsets with the power

I am struggling to use Ajax for submitting my zipped formsets. The code functions flawlessly without Ajax, but as soon as I try to incorporate Ajax, I encounter a ValidationError: [u'ManagementForm data is missing or has been tampered with'] Thi ...

Customizing AngularJS Scripts to Include Target Blank

I'm feeling a bit lost. I need to include a target="_blank" on my anchor link. The issue is that the anchor tag is linked to a script in angular. I am not familiar with this JavaScript framework. I have tried searching through the documentation for po ...

Fast screening should enhance the quality of the filter options

Looking to enhance the custom filters for a basic list in react-admin, my current setup includes: const ClientListsFilter = (props: FilterProps): JSX.Element => { return ( <Filter {...props}> <TextInput label="First Name" ...

Manipulating arrays and troubleshooting Typescript errors in Vue JS

I am attempting to compare the elements in one list (list A) with another list (list B), and if there is a match, I want to change a property/field of the corresponding items in list B to a boolean value. Below is the code snippet: export default defineCo ...

Issue with my lazyloading extension for Mootools

Seeking to create a plugin for sequential image downloads using MooTools. Assuming there are images with the img tag inside a div with the class imageswrapper. The goal is to download each image in order, one after the other until all images are loaded. ...

Utilizing D3 to fetch geographic data in the form of a TopoJSON file for U.S. counties

After retrieving a set of coordinates, the goal is to use D3 to find the corresponding county from a U.S. TopoJSON file. Here is an example code snippet: navigator.geolocation.getCurrentPosition(function(position) { let coordinates: [number, number] = [p ...

How come my Calendar is not showing up on the browser?

I came across a helpful guide on setting up a Calendar in HTML using JavaScript You can find it here: Unfortunately, the code I tried to use based on that guide isn't functioning as expected. <div class="row"> <div class="col-lg-4 text ...

Struggling to incorporate infinite scroll feature into JSON script that is already functioning smoothly

After developing a phonegap application, I created a page called photos.html to fetch photos from my server using JSON. However, despite successfully retrieving all the photos stored in my MySQL database on the server with JSON, I struggled to integrate In ...

Vuetify - custom filter for advanced datatable restrictions

Currently, I am faced with a challenge in filtering data from a table where the object names are similar and case sensitive, such as "A", "Aa", or "a". I am struggling to filter the data by these exact values when using a v-select bound to the search funct ...

Does the onChange event fire when the value is modified by the parent element?

let [number, set_number] = useState({x: 1}); <ChildComponent number={number} onUpdate={onUpdateFunction} </ChildComponent> set_number({x: 2}) After running set_number({x: 2}), will this action prompt the execution of onUpdateFunction refere ...

"Bootstrap-Wizard: How to troubleshoot the onPrevious function not working when used with an

I have been incorporating a bootstrap wizard into one of my applications, and I have encountered an issue. When attempting to utilize the index position of the tabs to achieve a specific goal, I found that it only works with the next button and not with th ...

Explain to me the process of passing functions in TypeScript

class Testing { number = 0; t3: T3; constructor() { this.t3 = new T3(this.output); } output() { console.log(this.number); } } class T3 { constructor(private output: any) { } printOutput() { ...

The Resharper guideline "Function Parameter" doesn't allow the usage of AngularJS service names

I have a question regarding naming conventions in my AngularJS app. Currently, all my service names start with an uppercase character. However, I am facing an issue where service parameters must match the service name, but Resharper's JavaScript "Func ...

Element in Vue not displaying when modal is hidden

Having trouble displaying a Vue component on a modal controlled by semantic ui. The Vue element is not loading or mounting properly. My setup involves Laravel and jQuery with some Vue elements intertwined. I have a hunch that the issue stems from the moda ...

managing the reloading of pages and navigating back and forth in the browser

In my project, I am using react and next.js to make API requests from a search bar and display a list of movies on the homepage. Each search result redirects me to a different page that shows detailed data related to the selected movie. However, the issue ...

The feature to hide columns in Vue-tables-2 seems to be malfunctioning

The issue I'm facing is with the hiddenColumns option not working as expected. Even when I set it to hiddenColumns:['name'], the name column remains visible. I've updated to the latest version, but the problem persists. UPDATE I am tr ...

Error: An unexpected TypeError occurred while attempting to fetch an array or collection from MongoDB Atlas

As a beginner in the world of Express and Mongoose, I am currently working on retrieving an object from MongoDB Atlas using Mongoose.Model for educational purposes. In CoursesModel.js, I have defined the schema for my collections and attempted to fetch it ...

What steps can be taken to safeguard the title of the document in the top window from being altered by any iframe or script?

My typical approach is to delete and redefine the title property like in the code snippet below: if (delete document.title) { Object.defineProperty(document, 'title', { get: getter, set: setter, enumerable: true, ...

How can I detect the scroll action on a Select2 dropdown?

Is there a way to capture the scrolling event for an HTML element that is using Select2? I need to be able to dynamically add options to my dropdown when it scrolls. Just so you know: I am using jQuery, and the dropdown is implemented with Select2. The ...

javascript implementing optional chaining for a single parameter

Is it possible to implement optional chaining on a single parameter? setAllProperties( Object.values(users).flatMap(({ properties }) => Object.values(properties) ) ); I am looking for a way to ensure that the properties folder exists in ...