如何使用异步查询读取待办事项列表并填充到网页任务列表
Vue 待办列表异步拉取接口数据实现方案
你需要在Vue实例的生命周期钩子中发起异步请求,拿到接口返回的待办数据后直接赋值给items即可,Vue会自动触发视图更新。以下是完整实现代码:
方案1:使用原生fetch(无需额外依赖)
new Vue({ el: '#app', data: { items: [{ text: "test1", completed: false, }], text: '', show: 'all', }, // 页面初始化完成自动拉取数据 created() { this.fetchTodoList() }, methods: { async fetchTodoList() { try { // 替换为实际的待办接口地址 const response = await fetch('https://你的待办接口地址') if (!response.ok) throw new Error('接口请求失败') const todoList = await response.json() // 直接赋值更新items,如需保留原有手动添加的test1,可改为 this.items = [...this.items, ...todoList] this.items = todoList } catch (error) { console.error('待办列表加载失败:', error) } } } })
方案2:使用Axios(项目已引入Axios时推荐)
// 需提前安装并引入Axios async fetchTodoList() { try { const { data: todoList } = await axios.get('https://你的待办接口地址') this.items = todoList } catch (error) { console.error('待办列表加载失败:', error) } }
注意事项
- 确保接口返回的单条待办数据结构和
items中已有的结构匹配,必须包含text和completed字段。如果接口字段名不一致,需要提前做格式转换:const formattedList = todoList.map(item => ({ text: item.接口返回的内容字段名, completed: item.接口返回的完成状态字段名 })) this.items = formattedList - 接口出现跨域报错时,需要后端配置CORS规则,或本地开发时配置代理转发
- 如需手动刷新列表,给按钮绑定
@click="fetchTodoList"即可触发请求
内容的提问来源于stack exchange,提问作者Kale
相关产品推荐
相关产品推荐

