useless noob
useless noob

Reputation: 11

How to render variables inside another variable in vue?

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

Upvotes: 1

Views: 288

Answers (2)

Isa Frimpong
Isa Frimpong

Reputation: 59

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;
    }
}

Upvotes: 0

Dhananjai Pai
Dhananjai Pai

Reputation: 6015

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.

Upvotes: 2

Related Questions