组件的实现包括两个部分:
- 一个包含了微信登录按钮的组件(
WechatLoginButton
),当用户点击按钮时,将调用微信的授权页面; - 一个处理微信授权回调的页面(
WechatAuthCallback
),该页面在微信授权后将收到微信返回的授权码,将授权码发送给服务器以获取用户信息。
组件使用了 v-if
和 v-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,
},
],
})