zoukankan      html  css  js  c++  java
  • 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)后,自动跳转页面到个人中心页(也可以配置跳转的参数)的示例

    <template>
        <view>
            <u-toast ref="uToast" />
        </view>
    </template>
    
    <script>
        export default {
            methods: {
                showToast() {
                    this.$refs.uToast.show({
                        title: '登录成功',
                        type: 'success',
                        url: '/pages/user/index'
                    })
                }
            }
        }
    </script>
    View Code

    三、跳转页面

    基本用法

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

    注意:仅限uView使用

    四、综合实践

    前端页面

     新建一个uView项目,参考文章:https://www.cnblogs.com/xiao987334176/p/15075858.html

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

    <template>
        <view class="wrap">
            <view class="title">
                这是主页
            </view>
        </view>
    </template>
    
    <script>
        export default {
            data() {
                return {
                    
                }
            }
        }
    </script>
    
    <style scoped>
        .wrap {
            padding: 40rpx;
        }
        .title {
            font-size: 40rpx;
            font-weight: 500;
        }
    </style>
    View Code

    修改pages/index/index.vue

    <template>
        <view class="wrap">
            <u-toast ref="uToast" />
            <view style="text-align: center;">
                <text class="title">登录</text>
            </view>
            <u-form :model="form" ref="uForm">
                <u-form-item label="用户名" label-width="100" prop="name">
                    <u-input v-model="form.name" placeholder="请输入用户名" />
                </u-form-item>
                <u-form-item label="密 码" label-width="100" prop="pwd">
                    <u-input v-model="form.pwd" type="password" :password-icon="passwordIcon" placeholder="请输入密码" />
                </u-form-item>
            </u-form>
            <u-button type="success" @click="submit">提交</u-button>
        </view>
    </template>
    
    <script>
        export default {
            data() {
                return {
                    passwordIcon: true,
                    form: {
                        name: '',
                        pwd: '',
                    },
                    rules: {
                        name: [{
                            required: true,
                            message: '请输入用户名',
                            // 可以单个或者同时写两个触发验证方式 
                            trigger: ['change', 'blur'],
                        }],
                        pwd: [{
                            required: true,
                            message: '请输入密码',
                            trigger: ['change', 'blur'],
                        }]
                    }
                }
            },
            methods: {
                login() {
                    let _this = this
                    let params = this.form
                    uni.request({
                        method: 'POST',
                        url: 'http://127.0.0.1:8000/login/', //仅为示例,并非真实接口地址。
                        data: params,
                        header: {
                            'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
                        },
                        success: (res) => {
                            // console.log(res);
                            if (res.data.status == '200') {
                                //跳转首页
                                _this.$refs.uToast.show({
                                    title: '登录成功',
                                    type: 'success',
                                    url: 'pages/home/index',
                                    duration: 500
                                })
                                // _this.goHome()
                            } else {
                                _this.$refs.uToast.show({
                                    title: res.data.message,
                                    type: 'error',
                                })
                            }
    
                        },
                        fail: (res) => {
                            console.log("调用失败", res)
                        }
                    });
                },
                goHome() {
                    console.log("执行goHome")
                    this.$u.route({
                        url: 'pages/home/index'
                    })
                    // uni.switchTab({
                    //     url: '/pages/home/index'
                    // });
                },
                submit() {
                    this.$refs.uForm.validate(valid => {
                        if (valid) {
                            console.log('验证通过');
                            this.login()
                        } else {
                            console.log('验证失败');
                        }
                    });
                }
            },
            // 必须要在onReady生命周期,因为onLoad生命周期组件可能尚未创建完毕
            onReady() {
                this.$refs.uForm.setRules(this.rules);
            }
        }
    </script>
    
    <style scoped>
        .wrap {
            padding: 40rpx;
        }
    
        .title {
            font-size: 40rpx;
            font-weight: 500;
        }
    </style>
    View Code

    后端接口

    这里使用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)
    View Code

    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'})),
    ]
    View Code

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

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

    启动uView项目,效果如下:

  • 相关阅读:
    vue.js 第二课
    vue.js学习(第一课)
    2016-11-14看张大神的微博总结
    这几天的工作总结:
    调了一天的兼容总结下
    鸭式辩论
    prototype 原型
    前端ps常用的小技巧
    Android的开始之相对布局
    Android的开始之线性布局
  • 原文地址:https://www.cnblogs.com/xiao987334176/p/15080481.html
Copyright © 2011-2022 走看看