开发前端App最先需要被实现的功能是:与本地主机上已经布置在IIS服务上的后端数据实现跨域(Cores)交互操作,这也是前端App作为前端工程性项目存在的根本意义和需求,因此需要首先对上一章中示例:22-09-24-04_uniAppVue3(初识HbuilderX之前移动前端App开发)进行重构,把网络后端数据实现跨域(Cores)交互实现重构为本地主机数据实现跨域(Cores)交互实现。

1 重构前端项目

1.1 重构main.js文件中的根域名为本地主机域名

//设置后端服务的根域名,“https://api-hmugo-web.itheima.net”可以提供JSON格式的数据,以供程序测试使用,本人以验证该后端服务能够提供数据。

//也可以把该根域名修改为自己,通过IIS部署的根域名例如:“http://localhost:8080”。

$http.baseUrl = 'http://localhost:8080'

1.2 重构pages\index\index.vue视图文件中的根域名为本地主机域名

<template>

<view class="content">

<view v-for="(list,index) in list" :key='index'>

编号:{{list.id}}角色名:{{list.roleName}}说明:{{list.description}}创建时间:{{list.createTime}}状态:{{list.enable}}

</view>

</view>

</template>

<script>

export default

    {

data()

        {

return {

title: 'Hello',

list: [],//第1步:声明数据局部变量,用于存储从服务器端获取的数据。

            }

        },

onLoad()

        {

//第3步:如果vue视图页面绑定有从指定方法获取的数据,则在vue视图页面渲染显示前,通过指定方法获取数据,为vue视图页面渲染显示提供数据支撑。

this.getFloorList();

        },

methods:

        {

//第2步:通过调用相对路由(“/api/public/v1/home/swiperdata”),获取该服务端控制器方法中的数据,并打印。

//注意:该相对路由(“/api/public/v1/home/swiperdata”)的绝对路由是:“https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata”。

//注意:该相对路由(“/role/get”)的绝对路由是:“http://localhost:8080/role/get”。

async getFloorList()

            {

//根据绝对路由在浏览器中的JSON编码格式的数据,重构“const”变量。

const {data:{status,response}} = await uni.$http.get('/role/get');

console.log(status);

if(status !== 200)

return uni.$showMsg();

this.list= response.data;

console.log(this.list);

            },

        }

    }

</script>

1.3 错误异常的执行结果

:“Access to XMLHttpRequest at 'http://localhost:8080/role/get' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.”,效果如下图所示:

uni 兼容axios ts uni-core_uni 兼容axios ts

2 重构后端项目

上述异常有两种解决方案:

  1. 通过向浏览器中安装指定的插件,参考:“(1条消息) 解决跨域问题:Access to XMLHttpRequest at ‘http://localhost:8080/xxx‘ No ‘Access-Control-Allow-Origin‘ head_一觉睡过头的菜鸡的博客_access to xmlhttprequest”,这种解决方案本人未测试。
  2. 重构后端项目:“22-09-22-02_UserVue(Vue服务器(后)端Swagger定义实现与发布部署)”

2.1 自定义管道中间件类:CorsMiddleware

/// <summary>

/// 【跨域访问中间件】

/// </summary>

/// <remarks>

/// 摘要:

///     该管道中间件类主要为了解决在前端uni-app项目跨域访问当前后端项目时,浏览器或App中会出现异常信息:

/// “Access to XMLHttpRequest at 'http://localhost:8080/role/get' from origin 'http://localhost:3000' has been blocked by CORS policy:

/// No 'Access-Control-Allow-Origin' header is present on the requested resource.”,从而导致前端uni-app项目不能与当前后端项目跨域的数据交互操作。

/// </remarks>

public class CorsMiddleware

    {

#region 拷贝构造方法

/// <summary>

/// 【下1个】

/// </summary>

/// <remarks>

/// 摘要:

///     .Net(Core)框架内置管道中的下1个管道中间件实例。

/// </remarks>

private readonly RequestDelegate _next;

///<param name="next">.Net(Core)框架内置管道中的下1个管道中间件实例。</param>

/// <summary>

/// 【拷贝构造方法】

/// </summary>

/// <remarks>

/// 摘要:

///    通过该构造方法中的参数实例,实例化.Net(Core)框架内置管道中的下1个管道中间件实例。

/// </remarks>

public CorsMiddleware(RequestDelegate next)

        {

            _next = next;

        }

#endregion

#region 方法

///<param name="context">HTTP上下文实例。</param>

/// <summary>

/// 【调用】

/// </summary>

/// <remarks>

/// 摘要:

///    通过该方法向.Net(Core)框架内置管道中集成当前管道中间件,从而解决指定错误异常:

///“Access to XMLHttpRequest at 'http://localhost:8080/role/get' from origin 'http://localhost:3000' has been blocked by CORS policy:

/// No 'Access-Control-Allow-Origin' header is present on the requested resource.”,从而导致前端uni-app项目不能与当前后端项目跨域。

///    最后如果.Net(Core)框架内置管道中在当前管道中间件之后,还有其它管道中间件被集成在.Net(Core)框架内置管道中,则.Net(Core)框架内置管道中继续向下执行下1个管道中间件。

/// </remarks>

public async Task Invoke(HttpContext context)

        {

if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))

            {

                context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

            }

await _next(context);

        }

#endregion

    }

2.2 重构 Program.cs

var app = builder.Build();

//把自定义管道中间中集成到.Net(Core)框架内置管道中,解决在前端uni-app项目跨域访问当前后端项目时,浏览器或App中会出现异常信息:

// “Access to XMLHttpRequest at 'http://localhost:8080/role/get' from origin 'http://localhost:3000' has been blocked by CORS policy:

// No 'Access-Control-Allow-Origin' header is present on the requested resource.”,从而导致前端uni-app项目不能与当前后端项目跨域的数据交互操作。

app.UseMiddleware<CorsMiddleware>();

2.3 重新对后端项目进行发布部署

   关于后端项目必须在最后进行发布部署操作,并通过IIS配置相应的网站,请查看本人的文章:“”。

2.4 部署完成后前端的执行结果

对以上功能更为具体实现和注释见:22-09-25-05_UserVue( uin-app本地主机数据跨域(Cors)数据交互实现之--后端)。

uni 兼容axios ts uni-core_App_02

3 通过第3方组件速构建vue视图页面。

遵循自定义组件的方式,把组件实例化为自定义标签,添加到指定的vue视图页面中,从而实现vue视图以多种形式对绑定的数据进行渲染显示。

遵循自定义组件的方式来实现,但为了速构建vue视图页面,HbuilderX为我们提供了另外一种好的选择,在项目中大量导入第3方组件,下面将通过“uni-table 表格”和“uni-tag 标签”组件的导入为示例,讲述怎样在项目通过导入第3方组件,来快速构建vue视图页面。

3.1 准备工作

    “uni-table 表格”第3方组件导入地址:uni-table 表格 - DCloud 插件市场。

    “uni-tag 标签”第3方组件导入地址:uni-tag 标签 - DCloud 插件市场。

3.1.1 为HbuilderX安装插件:“uniModules插件”

错误信息:“当前操作依赖插件【uni_modules】,请安装后再试”,如下图所示: 

uni 兼容axios ts uni-core_uni-app_03

出现上述错误的原因有两个:

  1. 已安装了“uniModules插件”,但未在HbuilderX开发环境生效。

这种方式的解决方案是:先关闭HbuilderX开发环境后,再打开HbuilderX开发环境,已安装了“uniModules插件”,即可生效。

2、HbuilderX开发环境未安装“uniModules插件”,下面将讲述“uniModules插件”的安装,安装步骤如下图所示:

uni 兼容axios ts uni-core_uni-app_04

查看是否是HbuilderX开发环境已经安装“uniModules插件”,但未生效。

uni 兼容axios ts uni-core_跨域Cores_05

       为HbuilderX开发环境已经安装“uniModules插件”,注意:安装完成后,要立即关闭HbuilderX开发环境后,再打HbuilderX开发环境,以防止上述错误的产生。

uni 兼容axios ts uni-core_跨域Cores_06

3.2 为当前项目导入第3方组件:“uni-table 表格”

3.2.1 打开网址:“uni-table 表格 - DCloud 插件市场

uni 兼容axios ts uni-core_App_07

3.2.2 导入后在项目中自动添加“Uni_modules”文件夹及其子文件夹和文件

公共组件和特定组件,为什么要这样分类,这将在“uni-tag 标签”第3方组件导入操作中进行说明,如下图所示:

uni 兼容axios ts uni-core_跨域Cores_08

3.3 为当前项目导入第3方组件:“uni-tag 标签”

    同上打开地址:uni-tag 标签 - DCloud 插件市场。,点击页面上的插件导入按钮。

公共组件复选框中的选择,再点击“合并”按钮,这也是我把子文件夹分为:公共组件和特定组件的主要原因,如下图所示。

uni 兼容axios ts uni-core_uni 兼容axios ts_09

将“uni-tag 标签”第3方组件导入项目,如下图所示:

uni 兼容axios ts uni-core_跨域Cores_10

3.4 最终形态的pages\index\index.vue视图文件

<template>

<view>

<view class="uni-container">

<uni-table ref="table" border stripe type="selection" emptyText="暂无更多数据">

<uni-tr>

<uni-th width="150" align="center">编号</uni-th>

<uni-th width="150" align="center">角色名</uni-th>

<uni-th width="150" align="center">说明</uni-th>

<uni-th width="150" align="center">创建时间</uni-th>

<uni-th width="150" align="center">状态</uni-th>

</uni-tr>

<uni-tr v-for="(item, index) in list" :key="index">

<uni-td>{{ item.id }}</uni-td>

<uni-td>

<view class="name">{{ item.roleName }}</view>

</uni-td>

<uni-td align="center">{{ item.description }}</uni-td>

<uni-td align="center">

<view v-if="item.createTime">{{ dateFormat(item.createTime) }}</view>

</uni-td>

<uni-td align="center">

<view v-if="item.enabled">

<uni-tag text="启用" type="success" style="width: 61px;text-align: center;" />

</view>

<view v-else>

<uni-tag text="禁用" type="error" style="width: 61px;text-align: center;" />

</view>

   

</uni-td>

   

</uni-tr>

</uni-table>

</view>

</view>

</template>

<script>

export default

    {

       

data()

        {

return {

title: 'Hello',

list: [],//第1步:声明数据局部变量,用于存储从服务器端获取的数据。

               

//下面两个为第3方“uni-tag”组件的局部变量,用于与当前vue视图页面中的指定标签进行绑定,为当前vue视图页面渲染显示提供数据支撑。

type: "default",

inverted: false,

            }

        },

onLoad()

        {

//第3步:如果vue视图页面绑定有从指定方法获取的数据,则在vue视图页面渲染显示前,通过指定方法获取数据,为vue视图页面渲染显示提供数据支撑。

this.getFloorList();

        },

methods:

        {

//第2步:通过调用相对路由(“/api/public/v1/home/swiperdata”),获取该服务端控制器方法中的数据,并打印。

//注意:该相对路由(“/api/public/v1/home/swiperdata”)的绝对路由是:“https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata”。

//注意:该相对路由(“/role/get”)的绝对路由是:“http://localhost:8080/role/get”。

async getFloorList()

            {

//根据绝对路由在浏览器中的JSON编码格式的数据,重构“const”变量。

const {data:{status,response}} = await uni.$http.get('/role/get');

console.log(status);

if(status !== 200)

return uni.$showMsg();

this.list= response.data;

console.log(this.list);

            },

           

//日期数据格式化输出渲染显示。

dateFormat(time) {

let date = new Date(time);

let year = date.getFullYear();

// 在日期格式中,月份是从0开始的,因此要加0,使用三元表达式在小于10的前面加0,以达到格式统一  如 09:11:05

let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;

let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();

let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();

let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();

let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

// 拼接

return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;

            },

                       

//下面两个为第3方“uni-tag”组件的方法,用于对上面定义的两个局部变量:type、inverted进行赋值,通过相对应的赋值,

//当前vue视图页面中的“uni-tag”组件在渲染显示时,显示为相对应的样式。

setType() {

let types = ["default", "primary", "success", "warning", "error"];

let index = types.indexOf(this.type);

types.splice(index, 1);

let randomIndex = Math.floor(Math.random() * 4);

this.type = types[randomIndex];

            },

setInverted() {

this.inverted = !this.inverted;

            },          

        }

    }

</script>

3.5 执行效果

uni 兼容axios ts uni-core_.Net6_11

      注意:

        到此为止“VSCodeVue3初识”系列已经结束,本人把word版的内容已经上传到了网上,有兴趣的讲到:“(3条消息) VSCodeVue3初识.docx-电子商务文档类资源-文库”下载。

对以上功能更为具体实现和注释见:22-09-25-06_uniAppVue3(uin-app本地主机数据跨域(Cors)数据交互实现之--前端)。