【技术求助】Vue.js用axios获取Spring Boot响应存入数组时split报错问题
问题场景
- 身份:Vue.js新手
- 开发目标:通过axios请求本地Spring Boot接口获取URL列表,将返回结果存入Vue数组并渲染到页面
- 异常表现:调用
split方法拆分接口返回内容时,控制台抛出类型错误
现有Vue.js逻辑代码
// JavaScript source code new Vue({ el: '#app', data() { return { urls: [], url: "" } }, mounted() { axios .get("http://localhost:91/all/URL") .then(response => (this.url = response.data, this.urls = this.url.split(","))) } })
现有页面HTML代码
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <meta charset="utf-8" /> <title>Home</title> </head> <body> <div id="app"> <ul v-for="url in urls"> <li> {{ url }} </li> </ul> </div> <script src="Script.js"></script> </body> </html>
控制台报错信息
Script.js:14 Uncaught (in promise) TypeError: this.urlfound.split is not a function at Script.js:14
报错原因
- 对接口返回值的类型预判错误:你以为接口返回的是逗号拼接的字符串,但实际Spring Boot接口默认返回JSON格式响应,axios拿到
response.data时已经自动完成反序列化,如果接口返回的是URL集合,response.data本身就是JS数组,数组类型没有字符串专属的split方法,直接调用就会抛出类型错误。 - 代码变量名不匹配:报错里出现的
this.urlfound和你在data中定义的url变量拼写不一致,说明实际运行的代码和贴出的版本有出入,取到的值为undefined时,也会触发“方法不存在”的报错。
修正方案
- 先在axios的then回调中打印
response.data和对应的数据类型,确认接口返回的实际结构,避免类型预判错误 - 如果接口返回的本身就是数组,不需要手动调用
split拆分,直接赋值给urls变量即可 - 编码时保持变量名拼写一致,避免因拼写错误取到undefined值
- 修正后的axios调用参考代码:
mounted() { axios .get("http://localhost:91/all/URL") .then(response => { console.log('返回数据内容:', response.data, '数据类型:', typeof response.data) // 接口直接返回数组的场景:直接赋值 if (Array.isArray(response.data)) { this.urls = response.data return } // 接口返回逗号拼接字符串的场景:转字符串后拆分 this.url = String(response.data) this.urls = this.url.split(",") }) }
- 渲染逻辑优化:原代码将v-for绑定在ul标签上会生成多个独立的ul节点,不符合常规DOM结构,建议将v-for绑定到li标签上,补充key属性避免Vue渲染告警,示例结构:
<ul> <li v-for="(item, index) in urls" :key="index">{{ item }}</li> </ul>
内容的提问来源于stack exchange,提问作者Michiel De Cap
相关产品推荐
相关产品推荐

