【vue】在vue中调用web api,并把请求结果绑定到element ui table中进行数据的展示(axios调用webapi)

it2025-09-24  1

前言

在之前我们已经搭建了vue开发环境、创建了第一个vue项目、使用了element ui前端UI框架,接下来将走进实际业务场景,创建一个新闻管理页面(component),并且通过axios请求web api,并把返回的数据绑定到新闻管理页面element ui table中进行展示,咱们一起开始吧

axios安装和使用

1、什么是axios

axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,主要是用于向后台发起请求(如:webapi)

2、安装axios和vue-axios

运行命令cnpm install axios --save安装axios

cnpm install axios --save

运行命令cnpm install --save vue-axios安装vue-axios

cnpm install --save vue-axios

3、在项目中全局引用axios

在主入口文件main.js中引用如下组件

//引如axios组件 import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios,axios);

4、通过axios调用webapi

请求webapi代码示例

this.axios .get(restweburl + "api/Article/GetAllArticles", { // 如果需要传参可以通过如下方式,也可以直接把参数拼接在url后边 //params: { //title: "", //}, }) .then((res) => { this.tableData = res.data; //使用state进行数据的存储和传输 this.$store.state.newsdatalist = res.data; }) .catch(function (error) { console.log(error); });

服务端webapi代码示例

[HttpGet("GetAllArticles")] public async Task<List<Article>> GetAllArticles() { List<Article> result = new List<Article>(); try { var articleRepository = new ArticleRepository(); //List<Article> articles = JsonConvert.DeserializeObject<List<Article>>(JsonListStr); result=await articleRepository.GetAllArticleAsync(); } catch (Exception ex) { RS.CreateErrorRS(ex.ToString()); } return result; }

请求完成后返回res.data为json数组,将返回的数据绑定到element table的data上

5、新闻管理页面(element table)

如下为新闻管理页面完整代码,代码中包括:

1、element ui

2、axios请求webapi,并返回json数组,绑定到element table上

3、通过vuex存储和传递数据(会在后续章节单独说明)

4、router路由(会在后续章节单独说明)

<template> <el-table :data="tableData" style="width: 100%"> <el-table-column prop="title" label="标题"> </el-table-column> <el-table-column fixed="right" label="操作" width="100"> <template slot-scope="scope"> <el-button @click="handleClick(scope.row)" type="text" size="small" >查看</el-button > <el-button type="text" size="small">编辑</el-button> </template> </el-table-column> </el-table> </template> <script> const restweburl = "http://localhost:5000/"; export default { created() { if (this.$store.state.newsdatalist.length == 0) { //const that=this; //用that解决函数内部this指向问题 this.axios .get(restweburl + "api/Article/GetAllArticles", { // 如果需要传参可以通过如下方式,也可以直接把参数拼接在url后边 //params: { //title: "", //}, }) .then((res) => { this.tableData = res.data; this.$store.state.newsdatalist = res.data; }) .catch(function (error) { console.log(error); }); } else { this.tableData = this.$store.state.newsdatalist; } }, methods: { handleClick(e) { this.$store.state.newsitem = e; console.log(this.$store.state.newsitem); this.$router.push({ path:'/NewsView' }) }, }, data() { return { tableData: [], }; }, }; </script> <style> </style>

至此,在vue中调用webapi就大概讲完了,如上描述如有错误,请大家及时在评论区指出,多谢

 

最新回复(0)