基本的 Vue 微信登录组件

组件的实现包括两个部分:

  1. 一个包含了微信登录按钮的组件(WechatLoginButton),当用户点击按钮时,将调用微信的授权页面;
  2. 一个处理微信授权回调的页面(WechatAuthCallback),该页面在微信授权后将收到微信返回的授权码,将授权码发送给服务器以获取用户信息。

组件使用了 v-ifv-else 指令来实现了根据登录状态显示不同的内容。

<!-- WechatLoginButton.vue -->
<template>
  <button class="wechat-login-button" @click="wechatAuth">
    <i class="fab fa-weixin"></i>
    <span v-if="!isAuthenticated">微信登录</span>
    <span v-else>已登录</span>
  </button>
</template>

<script>
import axios from 'axios'

export default {
  name: 'WechatLoginButton',
  data() {
    return {
      isAuthenticated: false,
    }
  },
  methods: {
    wechatAuth() {
      const redirect_uri = `${window.location.origin}/wechat-auth-callback`
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${process.env.VUE_APP_WECHAT_APPID}&redirect_uri=${encodeURIComponent(redirect_uri)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
    },
  },
}
</script>
<!-- WechatAuthCallback.vue -->
<template>
  <div class="wechat-auth-callback">
    <div v-if="!isAuthenticated">微信登录授权中,请稍候...</div>
    <div v-else>微信登录成功!</div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'WechatAuthCallback',
  data() {
    return {
      isAuthenticated: false,
    }
  },
  async created() {
    const code = this.$route.query.code
    if (code) {
      try {
        const response = await axios.get(`${process.env.VUE_APP_API_BASE_URL}/api/wechat-login?code=${code}`)
        if (response.data.success) {
          this.isAuthenticated = true
          // 更新用户信息
          this.$store.dispatch('updateUserInfo', response.data.userInfo)
        } else {
          console.error(response.data.message)
        }
      } catch (error) {
        console.error(error)
      }
    }
  },
}
</script>

请注意,此组件需要在路由中添加两个路由:

// router.js
import Vue from 'vue'
import Router from 'vue-router'
import WechatLoginButton from '@/components/WechatLoginButton.vue'
import WechatAuthCallback from '@/views/WechatAuthCallback.vue'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
    },
    {
      path: '/wechat-login-button',
      name: 'WechatLoginButton',
      component: WechatLoginButton,
    },
    {
      path: '/wechat-auth-callback',
      name: 'WechatAuthCallback',
      component: WechatAuthCallback,
    },
  ],
})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值