index.vue 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <template>
  2. <view
  3. class="login-container"
  4. :style="{
  5. background: `url(${getImageUrl(ICON_CFG.login_bg)}) no-repeat `,
  6. backgroundSize: '100%',
  7. }"
  8. >
  9. <button class="login-btn" open-type="getUserInfo" @getuserinfo="getUserInfo">
  10. <u-icon name="weixin-fill" color="#fefefe" size="28"></u-icon>
  11. 一键微信登录
  12. </button>
  13. </view>
  14. </template>
  15. <script>
  16. import { ICON_CFG } from '@/common/EnumConst';
  17. import { getImageUrl, setStorageObj } from '@/util';
  18. export default {
  19. name: 'login',
  20. props: {},
  21. data() {
  22. return {
  23. ICON_CFG,
  24. };
  25. },
  26. created() {
  27. },
  28. onLoad() {
  29. },
  30. methods: {
  31. getImageUrl,
  32. // 获取用户信息
  33. getUserInfo(e) {
  34. if (e.mp.detail.userInfo) {
  35. this.userInfo = e.mp.detail.userInfo;
  36. this.hasUserInfo = true;
  37. this.login();
  38. } else {
  39. uni.showModal({
  40. title: '警告',
  41. content: '您点击了拒绝授权,将无法进入小程序,请授权之后再进入!',
  42. showCancel: false,
  43. confirmText: '返回授权',
  44. success: function (res) {
  45. if (res.confirm) {
  46. console.log('用户点击了“返回授权”');
  47. }
  48. },
  49. });
  50. }
  51. },
  52. // 登录并获取用户信息
  53. login() {
  54. uni.login({
  55. provider: 'weixin',
  56. success: (loginRes) => {
  57. // 登录成功,获取用户code
  58. const { code } = loginRes;
  59. // 发送code到后台换取openId, sessionKey, unionId
  60. uni.request({
  61. url: `${process.env.UNI_API_PREFIX}/cp/usr/wx/login`, // 你的登录API地址
  62. method: 'POST',
  63. data: {
  64. code,
  65. ...this.userInfo,
  66. },
  67. success: (res) => {
  68. if (res.data && res.data.code === 200) {
  69. // 将用户信息和session存储到本地
  70. setStorageObj('userInfo', res.data);
  71. } else {
  72. uni.showToast({
  73. title: '登录失败',
  74. icon: 'none',
  75. });
  76. }
  77. },
  78. fail: () => {
  79. uni.showToast({
  80. title: '请求失败',
  81. icon: 'none',
  82. });
  83. },
  84. });
  85. },
  86. fail: (err) => {
  87. console.log('uni.login 接口调用失败,将无法正常使用开放接口等服务', err);
  88. uni.showToast({
  89. title: '登录失败',
  90. icon: 'none',
  91. });
  92. },
  93. });
  94. },
  95. },
  96. };
  97. </script>
  98. <style lang="scss" src="./index.scss" />;