How to access variables with dynamic names in Vue.js

I'm curious if it's possible to dynamically access variables from Vue’s data collection by specifying the variable name through another variable. For instance, consider the following example:

Here are some of the variables/properties:

var siteAdminVue = new Vue({
  el: "#siteAdmin",
  data: {
    tagtitle: "",
    tagparent: "",
    tagdesc: "",
    badgestitle: "",                    
    badgesdesc: "",               
    badgesprivilege: 0,                  
    newstitle: "",                    
    newsnotify: false,                  
    newscontent: "", 
}             

Now, let’s say I want to set some of these properties in one of my Vue methods:

var self = this;
var type = currentSection.toString().substr(4);
var selectElement = document.getElementById(currentSection + "select");

// Name of the Vue property, such as newstitle
var titleElement = type + "title";    

self.[titleElement]= selectElement.value;

Instead of using a switch statement to determine which property to set (newstitle, badgestitle, etc.), I am wondering if there is a way to store the property name in a variable and then use it to set the value. Is there a method to achieve this?

Thank you in advance!

Answer №1

Absolutely! Vue's data can be treated just like a traditional JavaScript object, allowing you to access and modify properties using dot or bracket notation.

If you haven't already, give it a try! Using

self[titleElement] = selectElement.value;
should get the job done perfectly.

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 Power of ZF2 with Restful APIs and Image

I am currently in the process of developing a website utilizing Zend Framework 2 in combination with AngularJS. The backend consists of a restful webservice running on ZF2, while AngularJS is used on the client side to interact with this webservice. My ne ...

Use jQuery to parse the JSON below and then showcase the information in an HTML table

Can anyone assist me with parsing the following JSON using jQuery and presenting it in an HTML table? I want to showcase the values of "key" and "doc_count" in an HTML table. Your help would be greatly appreciated. Please find the JSON data below: { ...

Is it possible to simultaneously update two entities using a single endpoint?

In order to update data in two different entities with a @OneToOne relationship between UserEntity and DetailsEntity, I need to create a function in my service that interacts with the database. Here are the entity definitions: UserEntity @Entity() export ...

Utilize the HTTP.get function to serve files in the img src attribute

I am facing an issue where my file can only be accessed if I include an x-authentication token in the header of the "GET" http request. Unfortunately, using a cookie is not an option in this case. This means I cannot simply call for the file by its URL in ...

How can jQuery input be incorporated in a form submission?

My current form includes a field for users to input an address. This address is then sent via jQuery.ajax to a remote API for verification and parsing into individual fields within a JSON object. I extract the necessary fields for processing. I aim to sea ...

Does the AJAX load more feature duplicate the existing data?

I've successfully implemented a PHP code that generates JSON data from WordPress posts in the database. By using AJAX, I'm able to load this JSON on my HTML page without any issues. Now, I want to enhance this functionality by adding a "Load Mo ...

Redirecting asynchronously in Node.js with no use of AJAX

I've been struggling with this issue for days and have already sought help, but nothing seems to be working. Whenever I attempt to redirect from a POST request in node, the browser doesn't respond. Here's how my app is structured: ./ confi ...

managing, modifying and removing information within the app.controller in AngularJS

I am currently facing a challenge with my Javascript code for a simple web application that involves AngularJS. Here is the snippet of code I am working on: app.filter('startFrom', function () { return function (input, start) { if (i ...

What is the process for integrating MongoDB into Vue.js 2?

I've been trying to install mongodb through npm, but I keep encountering the error message "Cannot find module 'fs'." Here is a snippet of my code: <script> const MongoClient = require('mongodb').MongoClient; export defau ...

Tricks for refreshing cached web page assets in the year 2023

So far, here are some of the old Cache Buster techniques I've come across: Adding a query string in the link src: /mstylesheet.css?cache_buster=12345 Changing the filename each time: /mstylesheet-12345.css Using Apache with Cache-Control "must-revali ...

Using the outer ng-repeat's object property to filter nested ng-repeat items

I'm currently working on nesting two ng-repeats with two separate JSON files. The goal is to filter the second ng-repeat based on parameters from the first ng-repeat. The first JSON file, $scope.matches, includes information about each match in the W ...

Using a pool.query with async/await in a for-of loop for PostgreSQL

While browsing another online forum thread, I came across a discussion on using async/await with loops. I attempted to implement something similar in my code but am facing difficulties in identifying the error. The array stored in the groups variable is f ...

Try to refrain from invoking effect within a component that is being conditionally rendered

I have a particular component that I am working with: const Component = () => { useEffect(() => { console.log('Executing useEffect in the Component') }, []) return <Text>element</Text>; } Whenever I conditionally re ...

Accessing data from arrays asynchronously using JavaScript

Update I have included actual code below, in addition to the concept provided earlier. Here is the async array access structure I am trying to implement: for (p = 0; p < myList.length ; p++){ for (k = 0; k < RequestList.length; k++){ i ...

The Vue.js expression is malfunctioning

I am encountering an issue with my expressions. I have successfully made a REST API call, which is functioning properly. The data is loading and being written to the console without any problems. However, I am facing difficulties when trying to display thi ...

Guide on how to smoothly navigate through an HTML page to a specific anchor point

Is there a way to use JavaScript to make the browser scroll the page to a specific anchor? In my HTML code, I have set either a name or id attribute like this: <a name="anchorName">..</a> or <h1 id="anchorName2">..&l ...

Guide to building a personalized autocomplete feature in vue js

Presently, I am using the buefy autocomplete feature, but it is causing a few problems. In the DepartmentDetail.vue file <template slot-scope="props"> <div class="container is-fluid"> <b-loading :is-full-page=" ...

Encountering a getMacChromiumEdgeDriverArchitecture error while using wdio/selenium-standalone-service

As I continue to learn WebDriverIO and adjust to MacOS, I encountered an error while trying to execute a spec file using "npm run test:wdio". The error message is as follows: > [email protected] test:wdio /Users/vinicius.correia/Desktop/dev/automat ...

The feature of option display is not supported on Safari browser

I am facing an issue with the functionality of two dropdown menus. The options in the second dropdown are supposed to be shown based on the selection made in the first dropdown. While this feature works perfectly in Chrome, it seems to be malfunctioning i ...

Steps to resolve the error message 'Argument of type 'number' is not assignable to parameter of type 'string | RegExp':

Is there a way to prevent users from using special symbols or having blank spaces without any characters in my form? I encountered an error when trying to implement this in my FormGroup Validator, which displayed the message 'Argument of type 'nu ...