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

Vue中如何渲染API请求返回的数组实现自动补全下拉菜单?

Vue自动补全下拉菜单渲染失效修复方案

核心问题排查

  • 你将methods配置项错误放在了data的返回值中:Vue的methods是组件根级配置项,和data同级,写在data内的方法不会被Vue实例代理,你在回调中修改的this.results不是响应式状态,所以页面不会触发重渲染。
  • 模板事件绑定语法错误:绑定@input事件时不需要加methods.前缀,直接调用方法名即可。
  • 非表单元素错误使用v-model:<p>标签属于静态展示元素,v-model仅适用于输入类表单元素,此处多余可以直接删掉。
  • v-for循环缺少唯一key值,会引发Vue渲染警告。

修复后完整代码

<template>
  <div>
    <input 
      type="text" 
      v-model="address" 
      placeholder="Start typing an address..." 
      @input="handleOnChange"
    />
    <ul v-if="results.length !== 0">
      <li v-for="(result, index) in results" :key="index">
        {{ result.streetLine  || ""}}
      </li>
    </ul>
    <p>
      {{results}}
    </p>
  </div>
</template>

<script>
const SmartyStreetsSDK = require("smartystreets-javascript-sdk");
const SmartyStreetsCore = SmartyStreetsSDK.core;
const Lookup = SmartyStreetsSDK.usAutocompletePro.Lookup;
// 注意替换下方[website-key]为你自己的实际密钥
const credentials = new SmartyStreetsCore.SharedCredentials([website-key]);
const clientBuilder = new SmartyStreetsCore.ClientBuilder(credentials).withLicenses(["us-autocomplete-pro-cloud"]).withBaseUrl("https://us-autocomplete-pro.api.smartystreets.me/lookup");
const client = clientBuilder.buildUsAutocompleteProClient();

export default {
  name: 'Autocomplete',
  data () {
    return {
      address: "",
      results: [{streetLine: "testing"}]
    }
  },
  methods: {
    handleOnChange() {
      const address = this.address
      console.log("this: ", this);
      if (address) {
        const lookup = new Lookup(address);
        client.send(lookup).then((response) => {
          console.log(response.result);
          this.results = response.result;
          console.log("databinding: ", this.results);
        }).catch(console.log)
      }
    }
  }
}
</script>

额外优化建议

可以加防抖逻辑,避免每次输入都发起API请求,减少不必要的接口调用,提升性能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 02:24:04