How can you display variables within another variable in Vue?

Is it possible for Vue to render variables inside another variable? If not, how can I achieve this functionality?



data() {
  return {
    SQL: {
      columns: ["id", "status", "post"],
      table: "users",
      limit: 10,
      query: "SELECT {{columns}} FROM {{table}} WHERE 1 LIMIT {{limit}}"
    }
  }
},
computed: {
  makeSQL: {
    return this.SQL.query; // expected result: "SELECT id, status, post FROM users WHERE 1 LIMIT 10"
  }
},

Answer №1

If you're looking to retrieve data, consider utilizing a getter function.

data() {
  return {
    SQL: {
      columns: ["id", "status", "post"],
      table: "users",
      limit: 10,
      get query() {
         return `SELECT ${this.columns.join(',')} FROM ${this.table} WHERE 1 LIMIT ${this.limit}`
      }
    }
  }
},
computed: {
  makeSQL: {
    return this.SQL.query; // should return "SELECT id, status, post FROM users WHERE 1 LIMIT 10"
  }
},

It's worth noting that this functionality is more of a JavaScript feature for generating a value based on other values within the object. There may not be a specific offering from Vue in this area.

To achieve the same result, you can utilize the computed property makeSQL to output

SELECT ${this.columns.join(',')} FROM ${this.table} WHERE 1 LIMIT ${this.limit}
.

Answer №2

Opting for computed variables is recommended in this situation. Transfer your query variable to a computed variable as shown below

computed: {
    query() {
        return 'SELECT ' + this.SQL.columns.join(',') + 'FROM ' + this.SQL.table + ' WHERE 1 LIMIT ' + this.SQL.limit;
    },
    createSQL() {
        return this.query;
    }
}

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

I need to investigate the reason behind the Edge Developer Tools appearing blank on our company's ASP.NET WebForms website. How can I determine the root cause of

Our current ASP.NET WebForms site relies on Microsoft Edge to function properly due to the way numerous links open in popup windows. Although a complete rewrite is necessary, this project has not yet been allocated resources for approval. Recently, I disc ...

Could someone kindly provide a detailed explanation of this Javascript code, breaking it down step

I'm currently learning Javascript and stumbled upon this code snippet. However, I'm having trouble grasping its functionality. Can someone please break it down for me step by step? var ar1 = [1, 5, 6, 4, 3, 5, 100, -20]; function funDo(ar) { ...

Exploring the Flatmap Promise Feature in JavaScript

I'm sure this question has been asked before, but is there a way to flatten a promise in JavaScript? For example: let justAPromise: Promise<something> = aPromise.flatMap( a => getAnotherPromise()); Or like this: let promiseOfPromise: Prom ...

Improve Email Regular Expression to Restrict Consecutive Periods

I'm not very good with regular expressions, so I decided to seek some help. Here's the regular expression I have: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.) ...

Modify one individual css style / tag

Currently, I have a large React application that is utilizing Material UI 4.3.0. I attempted to remove the margin-top style of label + .MuiInput-formControl within a select Mui component. To achieve this, I used the 'overrides' tag in my App.js ...

Is there a way to choose values from an object array in Angular?

Within my Angular (TypeScript) Project, I am working with an object array. let a = [{min:0, max:10},{min:10, max:810},{min:-10, max:110}]; My goal is to extract the minimum value of the min properties and the maximum value of the max properties. To achie ...

Exploring the depths of asynchronous calls in AngularJS with nested functions

Currently, I'm tackling a small project with AngularJS and finding myself tangled in multiple asynchronous calls that are starting to become chaotic. I know there must be a more efficient way to handle these calls, but I'm unsure of the best appr ...

JS method for gradually reducing the opacity of various div elements

I currently have two divs with background images styled using CSS. My goal is to create a loop that fades them in and out continuously. While attempting to achieve this effect, I encountered some issues and the following code snippet doesn't seem to ...

Issue with undefined bindingContext.$data in IE9 on knockout binding handler

I'm attempting to create a unique binding handler that applies role-based access to fields on a page. This custom handler uses the values of other observables from the viewModel to enable or disable input controls based on certain conditions. However ...

Tips for recognizing the custom element that initiated a core-ajax request (as indicated by the core-ajax response)

I am currently utilizing Polymer to create a series of custom elements, specifically post-cards. Each post-card contains a thumbnail image that expands to display the original image when clicked. The link to the original image is fetched from an ajax call ...

Understanding the concept of for loops in JavaScript and incorporating them in CSS styling

Hello there! I initially used this code to draw 12 lines, but now I am looking to incorporate a for loop and implement it in CSS. Can someone please guide me on how to proceed? <!DOCTYPE html> <html> <head> <style> #straigh ...

Adjust the width of the flex columns?

In one of my columns, I have a list that I'm splitting using CSS to wrap the data in the next column after a specific height. However, in the demo, you'll notice there's a lot of white space between the first and second columns. I'm uns ...

Providing data in response to a completed form submission

As a beginner, I'm attempting to accomplish the following task: a user selects options from three dropdown menus within a form, and the chosen values are then sent to another file for processing. action="process.php" method="post" In the processing ...

Extracting JSON data within ajax's success callback

I am currently working on parsing and displaying JSON data that is returned from a server. To accomplish this, I have set up an AJAX call that reads user input, sends it to a PHP page via POST method, and the PHP page var_dumps the array containing the JSO ...

Tips on integrating JavaScript with embedded Ruby code

I am attempting to generate a flash message that displays after a user clicks a link in my js.erb file. $('a').click(function(){ <% flash.now[:alert]= "Successfully added "%> this.innerHTML <% "to cart" %> }) M ...

Guide on accessing text content from a sibling div element using jQuery

There are several divs arranged on a page as shown below. If a user clicks a link within the UL .list-links, I want to capture the content inside: <span class="asa_portlet_title">Title here</span> and store it in a variable. I have attempted ...

Tips for refreshing an angularjs $scope using $.get jquery

Attempting to implement the code below using $scope: var scopes = "https://www.googleapis.com/auth/contacts.readonly"; setTimeout(authorize(), 20); function authorize() { gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, h ...

Linked selection options for state, city, and postal code

I have set up a cascading dropdown list - State -> City -> Pincode . Instead of fetching data from the database, I am using JSON. The dropdown functions smoothly on the local server, but experiences slowness on the web server. Here is a snippet of ...

Retrieving a value in the app component from a map using Angular

I have been struggling to display the values of ValueM, ValueR, and product in my app.component.html file. Can anyone offer a solution or tip to help me move forward? Thank you very much. app.component.ts forkJoin( this.service1.method1(filter1), ...

Angular data binding between an input element and a span element

What is the best way to connect input texts with the innerHTML of a span in Angular6? Typescript file ... finance_fullname: string; ... Template file <input type="text" id="finance_fullname" [(ngModel)]="finance_fullname"> <span class="fullnam ...