Home > front end >  How to use Vue data property inside JSON
How to use Vue data property inside JSON

Time:10-06

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?

CodePudding user response:

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://vuejs.org/v2/guide/computed.html

CodePudding user response:

You can try with computed:

new Vue({
  el: '#demo',
  data() {
    return {
      reports: [],
      searchId: "example",
      elasticSearchQuery: {
        query: {
          term: {
            ["searchId.keyword"]: this.searchId,
          },
        },
      },
    };
  },
  computed: {
    elSearch() {
      return this.elasticSearchQuery.query.term['searchId.keyword'] = this.searchId
    }
  },
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <p>{{elSearch}}</p>
</div>

  • Related