1

Does Vue can render variables inside another variable, and if not how can I reach this?


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; // should return "SELECT id, status, post FROM users WHERE 1 LIMIT 10"
  }
},

  • You can check this post it is explained: https://stackoverflow.com/questions/49614837/how-to-reference-data-variable-from-another-data-variable-in-vue-2 – Loki Sep 30 '19 at 14:55

2 Answers2

2

You could use a getter

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"
  }
},

PS: this is more of a javascript feature to generate a value based out of values of other keys in the object. Not sure if Vue has something specific to offer on this regard.

You could use the computed property makeSQL to return SELECT ${this.columns.join(',')} FROM ${this.table} WHERE 1 LIMIT ${this.limit} which should give you the same result.

Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25
0

It's better to use computed variables for this. Move your query variable to a computed variable like so

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