uni-app 发起请求,Toast 消息提示 ,跳转页面


一、发起请求

 发起网络请求

在各个小程序平台运行时,网络相关的 API 在使用前需要配置域名白名单

官方文档:https://uniapp.dcloud.io/api/request/request

下面说几个重点知识

data 数据说明

最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String。转换规则如下:

  • 对于 GET 方法,会将数据转换为 query string。例如 { name: 'name', age: 18 } 转换后的结果是 name=name&age=18
  • 对于 POST 方法且 header['content-type'] 为 application/json 的数据,会进行 JSON 序列化。
  • 对于 POST 方法且 header['content-type']  application/x-www-form-urlencoded 的数据,会将数据转换为 query string。

示例

uni.request({
    url: 'https://www.example.com/request', //仅为示例,并非真实接口地址。
    data: {
        text: 'uni.request'
    },
    header: {
        'custom-header': 'hello' //自定义请求头信息
    },
    success: (res) => {
        console.log(res.data);
        this.text = 'request success';
    }
});

二、Toast 消息提示 

此组件表现形式类似uni的uni.showToastAPI,但也有不同的地方,具体表现在:

uView的toast有5种主题可选
可以配置toast结束后,跳转相应URL

目前没有加载中的状态,请用uni的uni.showLoading,这个需求uni已经做得很好

官方网站:https://www.uviewui.com/components/toast.html

基本使用

以下为一个模拟登录成功后,弹出toast提示,并在一定时间(默认2000ms)后,自动跳转页面到个人中心页(也可以配置跳转的参数)的示例



三、跳转页面

基本用法

this.$u.route({
  url: 'pages/xxx/xxx'
})

注意:仅限uView使用

四、综合实践

前端页面

 新建一个uView项目,参考文章:

 在pages目录创建home文件夹,在home文件夹中创建index.vue,代码如下:





修改pages/index/index.vue





后端接口

这里使用python django框架作为后端接口,django版本3.5。这里仅限于对于django比较熟悉的人使用,小白路过。

使用Pycharm编辑器,创建一个demo项目。

views.py

from django.shortcuts import render
from rest_framework.viewsets import ViewSetMixin
from rest_framework import status
from django.http import JsonResponse
from rest_framework.views import APIView

# Create your views here.
class YueDuView(ViewSetMixin, APIView):
    def login(self, request, *args, **kwargs):
        # print(request.POST)
        user = request.POST.get('name')
        pwd = request.POST.get('pwd')
        print(user,pwd)
        if user=='xiao' and pwd=='1234':
            return JsonResponse({'status': status.HTTP_200_OK, 'data': [],'message':''},
                                status=status.HTTP_200_OK)
        else:
            return JsonResponse({'status': status.HTTP_403_FORBIDDEN, 'data': [],'message':'用户名或密码错误'},
                                status=status.HTTP_200_OK)

urls.py

from django.contrib import admin
from django.urls import path
from application import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', views.YueDuView.as_view({'post':'login'})),
]

注意:这是测试代码仅供测试使用。

启动django项目,使用Pycharm编辑器启动即可。

启动uView项目,效果如下: