Utilizing Vue Store Methods within an Array or Object

Imagine we have 5 identical buttons. Instead of duplicating them, I decided to make use of v-for.

methods: {
    a() {}, 
    b() {},
    ...
}

Replacing the individual buttons with:

<v-btn block color="primary" class="my-1" @click="a">A</v-btn>
<v-btn block color="primary" class="my-1" @click="b">B</v-btn>
<v-btn block color="primary" class="my-1" @click="c">C</v-btn>
<v-btn block color="primary" class="my-1" @click="d">D</v-btn>
<v-btn block color="primary" class="my-1" @click="e">E</v-btn>

Using:

 <v-btn v-for="(button, index) in buttons" :key="index"
      block color="primary" class="my-1" 
      @click="button.click">{{button.text}}
 </v-btn>

buttons: [
        { click: this.a, text: "A"},
        { click: this.b, text: "B"},
        { click: this.c, text: "C"},
        { click: this.d, text: "D"},
        { click: this.e, text: "E"},
      ]
  • The expected functionality works, but when rendering the buttons object, something seems off. Why are the clicks not registering?

    [ { "text": "A" }, { "text": "B" }, { "text": "C" }, { "text": "D" }, { "text": "E" } ]
    
  • Lets take it further and add a button with dynamic text (another data field)

    boolean: true
    F: "data1"
    
    f() {boolean ? this.F = "data1" : "data2"}
    <v-btn block color="primary" class="my-1" @click="F">{{F}}</v-btn>
    

This time, the result is:

[ { "text": "A" }, { "text": "B" }, { "text": "C" }, { "text": "D" }, { "text": "E" }, {} ]

The button text doesn't update, even though {{F}} shows the changes.

  • What might be causing this issue, and how can we tackle similar situations?

I attempted to create a method like setButtons to return an updated buttons array, yet when the data changes such as 'F', the object isn't refreshed accordingly.

Answer №1

If I understand correctly, you are looking to render a method within a @click event from a for-loop.

You can create a helper function to handle this situation.

In this example, the function bindFunction() will take the string button.click and return a corresponding function.

new Vue({
  el: "#app",
  data: {
        buttons: [
        { click: "toggleA", text: "A" },
        { click: "toggleB", text: "B" },
        { click: "toggleC", text: "C" },
        { click: "toggleD", text: "D" },
        { click: "toggleE", text: "E" }
      ]
  },
  methods: {
  bindFunction(f) {
      this[f]();
    },
    toggleA() {
      console.log("toggleA");
    },
    toggleB() {
      console.log("toggleB");
    },
    toggleC() {
      console.log("toggleC");
    },
    toggleD() {
      console.log("toggleD");
    },
    toggleE() {
      console.log("toggleE");
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <div v-for="(button, index) of buttons" :key="index">
      <button @click="bindFunction(button.click)">{{button.text}}</button>
    </div>
</div>

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

Utilizing dropbox.js in combination with OAuth 1: A step-by-step guide

I'm in the process of revamping a website that already exists, and although I have the code from the previous version, I'm encountering challenges replicating certain functionalities in the new iteration. Here's the situation: The user is ...

Vue.js renders components after the job is completed

Currently, I am dealing with a component that requires me to initiate a request using socket.io: <template> <h1>Please do not display until the socket responds</h1> </template> <script> export default { befor ...

"Enhance Your Communication: Utilize setTimeout in Ajax

Hey there, I could really use some help with the setTimeout function in my code. No matter what I try, it just doesn't seem to work. I'm currently working on a chat system where I need to send and receive messages (testing by opening 2 browser ...

Save the JWT token securely within a closure

Someone mentioned that the recommended way to store JWT tokens is as follows: access_token in the application memory (like closures) refresh_token in cookie entries (HttpOnly) Currently, my access_token is stored in localStorage and used for checking aut ...

Converting a string to regular text in JavaScript (specifically in ReactJS)

When I fetch data from an API, sometimes there are special characters involved. For example, the object returned may look like this: { question : "In which year did the British television series &quot;The Bill&quot; end?" } If I save t ...

Ajax is updating the information stored in the Data variable

Recently, I reached out to tech support for help with an issue related to Ajax not executing properly due to Access-Control-Allow-Origin problems. Fortunately, the technician was able to resolve the issue by adding a file named .htaccess with the code Head ...

Canvas Frustratingly Covers Headline

Several months ago, I successfully created my portfolio. However, upon revisiting the code after six months, I encountered issues with its functionality. Previously, text would display above a canvas using scrollmagic.js, and while the inspector shows that ...

Is there a way to send decimal values from a view to a controller using Vue.js?

I am encountering an issue when trying to pass decimal values from the view to the controller using Vue.js. Only decimal values seem to be arriving as NULL, while integer or string values work fine. Below is the code snippet: salvarProdutos: function ( ...

Adding an image within the body of text in a Django model, where both the text and image coexist

I am currently seeking a method to seamlessly insert an image within the text of my Django-powered blog. My goal is to achieve a layout similar to the one showcased in this example: https://i.stack.imgur.com/cFKgG.png The desired layout consists of two c ...

What is the best way to personalize Material UI elements, such as getting rid of the blue outline on the Select component?

Embarking on my journey of developing a React app, I made the decision to incorporate Material UI for its array of pre-built components. However, delving into the customization of these components and their styles has proven to be quite challenging for me ...

Express POST request body is required

I am starting to learn nodejs and express, and while reviewing some code I found this interesting snippet. Can someone please explain what it means and how I can send a POST request to it using cURL? There are no specified data fields. app.post('/&apo ...

IE11 Error: Script1003 expected but not found

I'm in the process of adding IE11 support, but encountering the following errors: SCRIPT1003: Expected ':' File: vendor.bundle.js, Line: 8699, Column: 8 SCRIPT5009: 'webpackJsonp' is undefined File: app.bundle.js, Line: 1, Colum ...

Disabling the "Master Detail" feature in MUI

Exploring the functionality of MUI's Master Detail feature raised a question about CSV exporting from a Data Grid. When trying to export to CSV with the Master Detail implementation, the export functionality seemed to break (as expected). It technical ...

Tips for Converting a JavaScript Array into JSON

I am dealing with data structured like this: "team": "Yankees" "players": ["jeter", "babe ruth", "lou gehrig", "yogi berra"] In my code, I extract these values from a form where they ar ...

What is the most effective method for pausing execution until a variable is assigned a value?

I need a more efficient method to check if a variable has been set in my Angular application so that I don't have to repeatedly check its status. Currently, I have a ProductService that loads all products into a variable when the user first visits the ...

Ajax request and the Ghostery extension in Firefox

I've implemented the following code to detect ad blockers like Ghostery: <script> var request = new XMLHttpRequest(); request.onreadystatechange = function() { if(request.readyState === 4 && request.status === 200 ) { ...

Refresh an iframe smoothly and without any visual distraction (using JavaScript)

Does anyone have a clever solution to dynamically refresh an iframe without the annoying flickering or flashing that usually occurs when the page reloads? Is it possible to incorporate a smooth blur-out and blur-in animation instead of the unappealing flic ...

Troubleshooting undefined results when dynamically loading JSON data with $scope values in AngularJS

My input field is connected to the ng-model as shown below. <div ng-app="myApp" ng-controller="GlobalCtrl"> <input type="text" ng-model="FirstName"> {{FirstName}} </div> In my controller, console.log $scope.FirstName shows m ...

The Grid within the Container is presented vertically rather than horizontally

I followed the coding style exactly as shown in a recent tutorial on YouTube, where the cards were displayed in a row. However, when I implemented it, they are appearing strangely in a column. Why is this happening? The default should be inline. Even afte ...

What is preventing WebRTC from re-establishing connection after being disconnected?

In my current React web application project, I am implementing a feature where users can engage in group calls using WebRTC through a NodeJS server running Socket.IO. The setup allows for seamless joining and leaving of the call, similar to platforms like ...