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

Auto play feature malfunctioning in Onsen-UI Carousel attribute settings

When utilizing onsen UI in my mobile web application, I encountered an issue with the autoplay property not functioning properly within the carousel. <ons-page> <ons-toolbar> <div class="left"> <ons-toolbar-button on ...

Incorrect SQL Server DateTime referencing when using .NET Core framework causes insertion and updating errors

Having some issues while trying to store DATETIME values in my SQL Server database using .NET Core & Entity Framework. The data is fetched from a VueJS API call and sent in this format: ... lastModified: "2019-10-28T10:54:07.556Z" ... Upon receiving the ...

In the matrix game, if a user chooses two balls of the same color, those two matching color patterns will be eliminated

I am currently working on a matrix game with the following condition: When a user selects two balls of the same color, they will destroy the two patterns with the same color. I have successfully implemented horizontal and vertical selection. However, I ...

The functionality of Nuxt's asyncData is restricted when attempting to access data from authorized express routes

Setting up an online store. I began with the products, which can be pulled without authorization but require it for editing. The process is smooth so far, probably because it's happening on the client side where authentication information is included ...

Injecting resolve values from UI router into Angular Jasmine tests

I am facing an issue in my Angular application where UI router resolves a promise into the controller. However, when attempting to test this controller using Karma, I receive an error about an unknown provider. How can I inject a mock object into the test ...

A basic problem involving appending content using jQuery

I have encountered a puzzling issue. Whenever I attempt to insert new content into the <div> element using my JS code, it briefly appears and then disappears abruptly. I am unsure of the reason behind this behavior. Is there a way to prevent this fr ...

Issue with AJAX call not functioning properly within PHP document

I've encountered an issue with a form that triggers an ajax call upon clicking the submit button. The ajax function is located within a PHP file as I need to populate some variables with data from the database. However, the before / success callbacks ...

Set an enumerated data type as the key's value in an object structure

Here is an example of my custom Enum: export enum MyCustomEnum { Item1 = 'Item 1', Item2 = 'Item 2', Item3 = 'Item 3', Item4 = 'Item 4', Item5 = 'Item 5', } I am trying to define a type for the f ...

Is there a way to invoke a C# method upon completion of the callback function in ScriptManager.RegisterStartupScript?

I am currently developing JavaScript methods that will be called from C# code. Once the JS methods are complete, I need to include C# code to send an email. Can anyone provide guidance on how to achieve this? ScriptManager.RegisterStartupScript(this, G ...

Issues with React's onSelect event functionality are persisting

Is there an event handler in React for the onSelect statement? For example, when a user highlights some text within a paragraph using their mouse, is there a way to trigger an event that extracts the highlighted text? import React, { Component } from &apo ...

Establish a connection to AWS by utilizing MQTT.js

Looking to create a web page that connects to an AWS server? While python-Paho-mqtt allows for the use of tls_set to add security certificates and more, how can we achieve the same with MQTT.js? And if unable to do so, what are the steps to run python-PAHO ...

Adding data from a database into an object in PHP for temporary use during the loading process can be achieved by following

I'm a beginner in PHP and I have some code that retrieves category type data from a database. I want to temporarily store this data in a PHP object while the page is loading. Initially, I need to load all predefined data and then use it when a certain ...

VueJS / v-html is displaying a blank page (Bokeh-html)

Especially as a newcomer to VueJS, I am currently in the process of trying to showcase a local HTML file within the Vue Application. The method I'm using to fetch the HTML file involves Axios, here's how it goes: <template> <div> ...

Dealing with onChange value in a date in reactjs is a common challenge that developers

I'm currently working on a basic date input component in React, but I've run into an issue when trying to change the value. Every time I update it, it always displays "1970-01-01". If anyone has any suggestions on how to fix this problem, I woul ...

What steps should I take to resolve this unexpected issue with svelte?

Whenever I attempt to execute the application, an error is consistently displayed to me. Here is a screenshot of the error: https://i.sstatic.net/jfo3X.png This issue always arises on the initial import type line, regardless of the content or arrangement ...

Using jQuery to incorporate a variable into JSON schema markup

For my current project, I am attempting to extract the meta description and incorporate it into JSON schema markup. However, I am facing difficulty in passing the variable properly into the JSON structure. My initial approach was as follows: <script&g ...

Vuetify does not support Tailwind CSS styles

Initially, I integrated Tailwind CSS into my project. However, during the development process, I decided to give Vuetify a try. After adding Vuetify along with vuetify-loader, I encountered an issue where Vuetify functionality was working fine but the styl ...

Rotating images with React

I am encountering an issue with implementing an image carousel in React. Previously, it worked perfectly when I was not using React, but now that I am migrating the page, I am facing an error. ** The carousel is located on the home page: ** const Home = ( ...

Building multiple files in React allows developers to divide their code

Can a React/Redux application be split into modules during webpack build? For example, having a set of components for users and another set for invoices. I want webpack to generate users.js and invoices.js that can be imported into index.html. If I make ch ...

creating a countdown timer for the carousel

While experimenting, I decided to create a basic carousel from scratch. Initially, I used onclick="function()" to cycle through the images. Later on, I attempted to replace it with onload="setInterval(function, 4000)", but it seems like something went wron ...