先看文档
https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
官方文档有两种方法
原因
- 由于前后端分离,使用后端返回url虽然简单,但可能会遇到跨域问题
- 那就使用前端嵌入二维码
- 好处是又方便又快又好管理
- 坏处是文档中的WxLogin正常引入js会没有,以下主要解决这个问题
<template>
<div class='inp' v-show='login_type === 1'>
<div>
<div id='login_container'></div>
</div>
</div>
</div>
</template>
<script >
//#region 微信登录
// 登录二维码地址
watch(login_type, (newValue) => {
// 监听,如果登录方式切换为微信,执行微信登录
if (newValue === 1) {
loginWechat();
}
});
onMounted(async () => {
// 以此种方式加载js,后面便可使用WxLogin.如果WxLogin在IDE显示红色,可忽视
const s = document.createElement('script');
s.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js';
s.async = true;
nextTick(() => {
document.body.appendChild(s);
});
});
const loginWechat = async () => {
// 微信登录, 获取并显示二维码
const qrcode = new window.WxLogin({
self_redirect:true,
id:'login_container',
appid: '你的id',
scope: 'snsapi_login',
redirect_uri: 'http://你的回调地址',
state: 'abb',
style: '',
stylelite: 1, // 自己测试一下0和1,看想要哪种显示方式
fast_login: 1
});
};
//#endregion
</script>
完成以上便可以vue3中正确嵌入并渲染微信登录二维码