sylllys
sylllys

Reputation: 13

How to use Vue data property inside JSON

In the below Vue code under data properties, how to set the json field:elasticSearchQuery.query.term."searchId.keyword" with a vue data property: searchId?

const app = Vue.createApp({
    data() {
      return {
        reports: [],
        searchId: "example",
        elasticSearchQuery: {
          query: {
            term: {
              "searchId.keyword": "example",
            },
          },
        },
      };
    },
    methods: {
      getElasticReports() {
  
        axios
          .post("http://localhost:9200/search-reports/_search", this.elasticSearchQuery, {
            headers: {
              "Content-Type": "application/json",
            }
          })
          .then((response) => (this.reports = response.data.hits.hits))
          .catch((error) => console.log(error));
      },
    },
  });
  
  app.mount("#app");

when I set "searchId.keyword": "example", it works fine however "searchId.keyword": this.searchId, does not work, I get 400 bad response

how should I pass a vue data property into the json field?

Upvotes: 1

Views: 232

Answers (1)

Mark Minkoff
Mark Minkoff

Reputation: 83

Data variables in vue cannot access other data variables during run time. Make the elasticSearchQuery a computed property.

computed: {
    elasticSearchQuery() {
        return {
            query: {
            term: {
              "searchId.keyword": this.searchId,
            }
          }
        }
    }
}

Read more about it here: https://v2.vuejs.org/v2/guide/computed.html

Upvotes: 2

Related Questions