You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue data属性的JSON结构中引用其他同层级data属性值

错误原因

你在data()返回的对象中直接写"searchId.keyword": this.searchId无法拿到正确值,因为data函数执行初始化时Vue实例还未构建完成,此时this不指向当前实例,拿到的searchId为undefined,传给ElasticSearch的查询参数不符合要求就会返回400错误。

解决方案

方案1:使用计算属性存储查询条件(推荐)

将elasticSearchQuery移到computed配置项中,计算属性会自动响应searchId的变化,始终返回最新的查询参数:

const app = Vue.createApp({
    data() {
      return {
        reports: [],
        searchId: "example",
      };
    },
    computed: {
      elasticSearchQuery() {
        return {
          query: {
            term: {
              "searchId.keyword": this.searchId
            },
          },
        }
      }
    },
    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");

方案2:请求发起前动态赋值

如果不需要实时同步查询条件,可以在发起请求前手动给查询字段赋值:

const app = Vue.createApp({
    data() {
      return {
        reports: [],
        searchId: "example",
        elasticSearchQuery: {
          query: {
            term: {
              "searchId.keyword": "",
            },
          },
        },
      };
    },
    methods: {
      getElasticReports() {
        // 发起请求前赋值最新的searchId
        this.elasticSearchQuery.query.term["searchId.keyword"] = this.searchId
        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");

两种方案按需选择即可,计算属性方案适配查询条件多、需要响应式更新的场景,动态赋值方案适配仅请求时需要同步参数的场景。

内容的提问来源于stack exchange,提问作者sylllys

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 04:57:04