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項目,效果如下:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章