How to pass a data property as a function argument in Vue.js

Instead of using a few methods that are structured like this:

showDiv1(){ 
    this.showDiv1 = true
},
showDiv2(){ 
    this.showDiv2 = true
}

I am attempting to consolidate them into one method like so:

showElements(...elementNames){
     elementNames.forEach(name => {
           this.$data.name = true
     })
}

The concept behind this approach is to pass one or more properties from the data object, and when calling the method, those elements will be displayed on the screen.

In my data object, the structure looks something like this:

  data() {
      return {
           div1 = false,
           div2 = false
      }
  }

Within the HTML, I attempted to trigger the function on click in a couple of different ways:

  <button @click="showElements('div1')">Show<button>
  <button @click="showElements(div1)">Show<button>
  <div v-if="div1">
       <p>Hello</p>
  </div>    

However, nothing seems to happen upon clicking the buttons.

Answer №1

It appears you are encountering a syntax error. Instead of setting up your data object in this manner:

 data() {
      return {
           item1 = true,
           item2 = false
      }
  }

You should structure it like this:

 data() {
      return {
           item1: true,
           item2: false
      }
  }

Ensure that the syntax aligns with an object format within the data object. Then, you can reference it in this way:

 <button @click="displayItems(item1)">Display<button>

Furthermore, when retrieving the data, there is no need to include $data. Simply use 'this.name' to access your data.

Answer №2

When it comes to accessing dynamic property names, bracket notation is the way to go:

displayItems(...itemNames){
     itemNames.forEach(item => {
           this[item] = true
     })
}

To use this method, follow this example:

<button @click="displayItems('item1')">Display<button>

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

Holding off on executing the event handler until the completion of another function

On our website, we've integrated a 3rd party solution that cannot be directly updated. However, I can insert my own JavaScript code to manipulate the solution. This third-party tool includes a button that triggers an AJAX request. Before this request ...

Having trouble passing an array from PHP to JavaScript

I'm facing an issue with the following code snippet: <?php $result = array(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ $result[] = sprintf("{lat: %s, lng: %s}",$row['lat'],$row['lng']);} ?> <?php $resultAM = joi ...

What is the most efficient way to apply a single click handler instead of using multiple click handlers for the same

Check out the project I'm currently working on by following this link: The link provided above contains a list of clickable colors available on the right side. When a user clicks on a color, the images on the left side change accordingly. Below is t ...

Scan for every header tag present and verify the existence of an id attribute within each tag. If the id attribute is absent, insert

Looking to locate all header tags within the content and verify if each tag has an id attribute. If not, then jQuery should be used to add the id attribute. Here is the code snippet: var headings = $("#edited_content").find("h1,h2,h3,h4,h5,h6"); $.each( ...

Errors can arise in Discord.js when encountering "undefined" before the first array object in an embed

I am currently in the process of creating a Discord bot command that allows users to construct their own city. I am encountering an issue with a list command that is supposed to display all the roads and places built within the city. However, each list kee ...

Exploring the power of $j in JavaScript

Could someone please explain what the $J signifies in this snippet of javascript code? if ($J('.searchView.federatedView.hidden').attr('style') === 'display: block;' || $J('.searchView.federatedView.shown').length ...

Attempt to efficiently register components automatically on a global scale in Vue by utilizing the powerful combination of Laravel-Mix and Webpack

In my previous projects with Vue, which were based in a Laravel-Mix/Webpack runtime environment, I used to individually register components and views as needed. This was done by importing them and extending Vue: import BaseButton from './components/Ba ...

I am encountering undefined values when utilizing momentjs within Angular

My project is utilizing angular and momentJS, with the addition of the angular-moment library. You can find my current progress in this fiddle However, I am encountering an error when trying to use moment in a controller method: TypeError: undefined is n ...

The function Mediarecorder.start() is experiencing issues on Firefox for Android and is not functioning

Recently, I've been facing a peculiar issue while developing a web application. The purpose of this app is to capture about 10 seconds of video intermittently from the device webcam and then upload it to a server. For this functionality, I utilized th ...

Troubleshooting: jQuery's clone( true ) function fails to function properly with dynamic

Consider this scenario: $.fn.foo = function() { var $input = $('<input type="text"/>'); var $button_one = $('<button>One</button>'); var $button_two = $('<button>Two</button>'); ...

Develop a novel function

I am working on a new Order page where users can select a category, then a service, and fill out the quantity field for their order. I have an idea to create a function using @if and @else statements. In this function, I want to display the quantity fiel ...

Adding numerous pieces of data into the Shopware 6 database through the use of the Administration for handling Many

I recently developed a plugin within the administration of Shopware 6 and I am encountering an issue while trying to insert multiple products associated with vehicles into the database. The specific problem arises when attempting to add '92961afbc50e4 ...

What is the correct way to define the field name in the update() function of Mongoose?

When attempting to update every field contained in the dataToChange object, I encountered a problem where the update() method does not take the key name from the outside. Instead, it looks for a "key" field within the database's object. How can I work ...

Press on a rectangle inside an HTML5 SVG program

I'm currently developing a web application that utilizes the svg and Raphael library: workflowEditor.show(); var myList = document.getElementsByTagName("rect"); for (var a = 0; a < myList.length; a++) { myList[a].addEventListener("OnClick", f ...

Untangling REGEX URLs for Effective Filtering

I am currently working on creating a filter for a video list. I have successfully put together a string that includes all the values selected by the user for filtering. Right now, I am passing this string as a parameter through the URL. For example: NOTE ...

The CSS for the ajax call functions correctly on desktop devices but is not displaying properly on mobile devices

My ajax call is facing an issue where the CSS classes for a loader and overlay are only being applied in desktop view, not mobile view. I am unsure of what mistake I may be making. Can someone help me resolve this problem? Here is the ajax call: function ...

The extended class possesses a distinct type from the base class, which is reinforced by an interface

Is it possible to write a method that is an extension of a base class, but with a different return type, if supported by the shared interface, without adding a type declaration in class 'a'? In practical terms, classes a & b exist in JavaScript ...

Is there a way to retrieve the file path of the file that is imported using an alias in Vite (Vue3)?

Hello! I have a few inquiries. Is it feasible to obtain the file path of the file utilizing an alias for import in Vite (Vue3)? Setup Here's the directory structure I'm using, purely for illustrative purposes: src/ module_a/ some_ ...

Utilizing jQuery to convert object properties into a table

Here is the table structure I am working with: <table> <thead> <tr> <th>Loan Type</th> <th>Amount Borrowed</th> <th>Current Payment< ...

Dynamically generate Nav List Items in Vue.js based on the paths of route children

I am attempting to create a dynamic navigation list using the routes defined in my routes.js: const routes = [ { path: '/', component: () => import('layouts/MainLayout.vue'), children: [ { ...