123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144 |
- /**
- * 请求方法使用示例
- */
- import { userApi, contentApi, promiseApi } from '@/utils/api';
- // 示例1:使用回调方式调用登录接口
- export function loginExample() {
- // 准备登录数据
- const loginData = {
- username: 'test',
- password: '123456'
- };
-
- // 调用登录接口
- userApi.login(loginData, (res, err) => {
- if (err) {
- console.error('登录失败', err);
- uni.showToast({
- title: '登录失败',
- icon: 'none'
- });
- return;
- }
-
- if (res.data && res.data.code === 0) {
- console.log('登录成功', res.data);
- // 保存用户信息
- uni.setStorageSync('userInfo', JSON.stringify(res.data.data));
- uni.showToast({
- title: '登录成功',
- icon: 'success'
- });
- } else {
- console.error('登录失败', res.data.msg);
- uni.showToast({
- title: res.data.msg || '登录失败',
- icon: 'none'
- });
- }
- });
- }
- // 示例2:使用Promise方式调用登录接口
- export async function loginPromiseExample() {
- try {
- // 准备登录数据
- const loginData = {
- username: 'test',
- password: '123456'
- };
-
- // 调用登录接口
- const res = await promiseApi.login(loginData);
-
- if (res.data && res.data.code === 0) {
- console.log('登录成功', res.data);
- // 保存用户信息
- uni.setStorageSync('userInfo', JSON.stringify(res.data.data));
- uni.showToast({
- title: '登录成功',
- icon: 'success'
- });
- return res.data.data;
- } else {
- console.error('登录失败', res.data.msg);
- uni.showToast({
- title: res.data.msg || '登录失败',
- icon: 'none'
- });
- return null;
- }
- } catch (error) {
- console.error('登录请求异常', error);
- uni.showToast({
- title: '网络异常,请稍后重试',
- icon: 'none'
- });
- return null;
- }
- }
- // 示例3:在页面中使用
- // 在Vue组件中使用示例
- /*
- export default {
- data() {
- return {
- username: '',
- password: ''
- };
- },
- methods: {
- // 回调方式登录
- handleLogin() {
- const loginData = {
- username: this.username,
- password: this.password
- };
-
- userApi.login(loginData, (res, err) => {
- // 处理登录结果
- if (err) {
- this.$toast('登录失败');
- return;
- }
-
- if (res.data && res.data.code === 0) {
- this.$toast('登录成功');
- // 跳转到首页
- uni.switchTab({
- url: '/pages/index/index'
- });
- } else {
- this.$toast(res.data.msg || '登录失败');
- }
- });
- },
-
- // Promise方式登录
- async handleLoginPromise() {
- try {
- const loginData = {
- username: this.username,
- password: this.password
- };
-
- const res = await promiseApi.login(loginData);
-
- if (res.data && res.data.code === 0) {
- this.$toast('登录成功');
- // 跳转到首页
- uni.switchTab({
- url: '/pages/index/index'
- });
- } else {
- this.$toast(res.data.msg || '登录失败');
- }
- } catch (error) {
- this.$toast('网络异常,请稍后重试');
- }
- }
- }
- }
- */
|