Taro 开发微信/抖音/... 小程序的时候的登录逻辑

今天总结一下 开发小程序的登录的问题

我们经常会看到 市面上的一些小程序 当点击到 一些涉及到 用户信息的功能或者页面的时候 我们跳转到登录页面 当用户登录成功以后 再给用户返回到原来浏览的页面,这样的交互是非常好的

这样既可以引导用户 很好的登录 也可以有很好的交互

如果你是一个前端开发 应该能明白我的逻辑 今天我们就来实现这个逻辑 我把代码贴在下面 以后开发微信小程序 都可以这样去写

我们准备一个登录页面

代码

复制代码
<template>
  <view class="login-container">
    <div class="main">
      <div class="head">
        <div class="title">欢迎使用抖票票</div>
        <div class="desc">未注册过的抖音号将自动创建账号</div>
      </div>
      <div class="btns" @tap="onDouyinLogin">
        <nut-button
          block
          :disabled="!isAgreeAccord"
          color="linear-gradient(to right, #ff6034, #ee0a24)"
          ><div>抖音号登录</div></nut-button
        >
      </div>
      <div class="accord">
        <div class="checkbox">
          <nut-checkbox v-model="isAgreeAccord"></nut-checkbox>
        </div>
        <div class="txt">
          <div class="a">已阅读并同意</div>
          <div class="b" @click="skipUserAgreement">《用户协议》</div>
          <div class="b" @click="skipPrivacyAgreement">《隐私协议》</div>
        </div>
      </div>
    </div>
  </view>
</template>

<script setup lang="ts">
import Taro from "@tarojs/taro";
import { ref, onMounted } from "vue";
import * as loginApi from "../../api/login";
import { storeToRefs } from "pinia";

import { useUserStore } from "../../store";
import { useDidShow } from "@tarojs/taro";
const router = Taro.useRouter();
const userStore = useUserStore();
const { Userinfo, shareUserId } = storeToRefs(userStore);

const isAgreeAccord = ref(false);
const sourceUrl = ref("");
const code = ref("");
onMounted(() => {
  if (router.params.url) {
    sourceUrl.value = decodeURIComponent(router.params.url);
  }
});
useDidShow(() => {
  Taro.login({
    success: async function (res) {
      if (res.code) {
        Taro.showLoading({ title: "加载中", mask: true });
        code.value = res.code;
        Taro.hideLoading();
      } else {
        // Taro.showToast({
        //   title: "获取code失败",
        //   icon: "error",
        //   duration: 2000,
        // });
      }
    },
  });
});
const onDouyinLogin = async () => {
  try {
    Taro.showLoading({ title: "登录中...", mask: true });
    const userRes = await Taro.getUserProfile({ desc: "获取用户信息" });
    console.log(userRes, "----");
    // return;,

    let loginRes = await loginApi
      .dyLogin(code.value, userRes.userInfo, shareUserId.value)
      .catch((error) => {
        console.log(error);

        Taro.showToast({
          title: error.errMsg,
          icon: "error",
          duration: 2000,
        });
      });
    if (loginRes) {
      userStore.setToken(loginRes["token"]);
      userStore.getUserinfo();
      // 跳转至原url
      toSourceUrl();
    } else {
      Taro.showToast({
        title: "获取code失败",
        icon: "error",
        duration: 2000,
      });
    }
    Taro.hideLoading();

    // Taro.login({
    //   success: async function (res) {
    //     if (res.code) {
    //       Taro.showLoading({ title: "加载中", mask: true });
    //       const userRes = await Taro.getUserProfile({ desc: "获取用户信息" });
    //       console.log(userRes, "---------------");

    //       let loginRes = await loginApi
    //         .dyLogin(res.code, userInfo)
    //         .catch((error) => {
    //           Taro.showToast({
    //             title: error.errMsg,
    //             icon: "error",
    //             duration: 2000,
    //           });
    //         });
    //       // 如果登录成功
    //       if (loginRes) {
    //         userStore.setToken(loginRes["token"]);
    //         userStore.getUserinfo();
    //         // 跳转至原url
    //         toSourceUrl();
    //       }
    //       Taro.hideLoading();
    //     } else {
    //       Taro.showToast({
    //         title: "获取code失败",
    //         icon: "error",
    //         duration: 2000,
    //       });
    //     }
    //   },
    // });
  } catch (error) {
    console.log(error);

    Taro.showToast({
      title: "拒绝授权",
      icon: "error",
      duration: 2000,
    });
    return error;
  }
};
const toSourceUrl = () => {
  const url = sourceUrl.value;
  if (!url) {
    Taro.navigateBack();
    return;
  }
  const tabbarPageList = [
    "/pages/home/index",
    "/pages/cinema/index",
    "/pages/order/index",
    "/pages/my/index",
  ];
  if (tabbarPageList.includes(url)) {
    Taro.switchTab({
      url: sourceUrl.value,
    });
  } else {
    Taro.redirectTo({
      url: sourceUrl.value,
    });
  }
};
const skipUserAgreement = () => {
  Taro.navigateTo({
    url: "/pages/user-agreement/index",
  });
};
const skipPrivacyAgreement = () => {
  Taro.navigateTo({
    url: "/pages/privacy-agreement/index",
  });
};
</script>

<style lang="scss">
.login-container {
  display: flex;
  flex-direction: column;
  padding: 5rem 0;
  .main {
    display: flex;
    flex-direction: column;
    padding: 2rem;
    .head {
      display: flex;
      flex-direction: column;
      text-align: center;
      .title {
        font-size: 0.8rem;
        color: #15181d;
        font-weight: 500;
        line-height: 1.6rem;
      }
      .desc {
        font-size: 0.6rem;
        line-height: 1.2rem;
        color: #858a99;
      }
      margin-bottom: 1.5rem;
    }
    .btns {
      .nut-button {
        border: none !important;
      }
    }
    .accord {
      display: flex;
      flex-direction: row;
      height: 1rem;
      margin-top: 1.5rem;
      align-items: center;
      justify-content: center;
      .checkbox {
        width: 1rem;
      }
      .txt {
        display: flex;
        flex-direction: row;
        .a {
          font-size: 0.6rem;
          color: #858a99;
        }
        .b {
          font-size: 0.6rem;
          margin: 0 0.2rem;
          color: #ee0a24;
        }
      }
    }
  }
}
</style>

最重要的代码是其中的一个方法

复制代码
const toSourceUrl = () => {
  const url = sourceUrl.value;
  if (!url) {
    Taro.navigateBack();
    return;
  }
  const tabbarPageList = [
    "/pages/home/index",
    "/pages/cinema/index",
    "/pages/order/index",
    "/pages/my/index",
  ];
  if (tabbarPageList.includes(url)) {
    Taro.switchTab({
      url: sourceUrl.value,
    });
  } else {
    Taro.redirectTo({
      url: sourceUrl.value,
    });
  }
};

这个方法 就是 跳转到用户浏览的页面 当然 这个 页面需要传到登录页面

因为 这是一个统一的判断功能 所以我们 可以使用 vue 中的 mixin 方式

我来写一个js文件

这个文件 其实就是导出了一个对象 是一个 onShow 生命周期函数 里面判断了 token 当然可以用别的 来判断是否登录

以上就是准备的方法

我们需要在那个页面中登录 就把这个mixin 使用到哪里

我来举个例子

个人中心页面需要用户登录

我就在这个页面中引入 这个方法

使用mixins 点击这个页面 没有token 就会跳转到登录页面 登录成功了 就会返回个人中心页面

其实这个没啥难得 一个很巧妙得登录方式和判断方式而已

只要页面需要登录 把上述代码 复制一份 就可以

相关推荐
云起SAAS19 小时前
倒班日历助手抖音快手微信小程序看广告流量主开源
微信小程序·小程序·ai编程·看广告变现轻·倒班日历助手
sheji341621 小时前
【开题答辩全过程】以 基于微信小程序的失物认领系统为例,包含答辩的问题和答案
微信小程序·小程序
qq_256847888621 小时前
08cms房产多城市版最新v8.7含小程序及装修网的安装及配置方法整理出来希望能帮到大家
小程序·08cms房产系统源码·08cms装饰网门户系统·08cms 房产门户系统源码
风月歌21 小时前
python项目之摄影竞赛小程序
python·mysql·小程序·毕业设计·源码
云云只是个程序马喽1 天前
2026年短剧系统开发搭建全流程教程(小程序+APP自营/红果模式/广告联盟/海外多语言)
小程序
计算机毕设指导61 天前
基于微信小程序的网络安全知识科普平台系统【源码文末联系】
java·spring boot·安全·web安全·微信小程序·小程序·tomcat
陈思杰系统思考Jason1 天前
系统思考:结构性重复
百度·微信·微信公众平台·新浪微博·微信开放平台
天***88962 天前
小程序婚纱店摄影楼预约婚庆礼展示,小程序开发定制,会员下单档期系统
小程序
说私域2 天前
开源AI智能名片链动2+1模式商城小程序下短视频电商变现与广告变现的对比研究
人工智能·小程序
陈思杰系统思考Jason2 天前
企业经营误区:被动应激与主动经营
百度·微信·微信公众平台·新浪微博·微信开放平台