以下是基于uni-app实现微信小程序一键登录和退出登录功能的示例代码
1. 在 App.vue 中引入 wxLogin 组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <template> <div> <wx-login @login= "onlogin" @logout= "onlogout" > </wx-login @login= "onlogin" @logout= "onlogout" ></div> </template> <script> import WxLogin from & #39;@/components/WxLogin.vue'; export default { components: { WxLogin, }, methods: { onLogin(userInfo) { // 处理登录成功后的逻辑 }, onLogout() { // 处理退出登录后的逻辑 }, }, }; </script> |
2. 在 components 目录下创建 WxLogin.vue 组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <template> <div> <button v- if = "!islogged" @click= "login" >一键登录 <button v- if = "islogged" @click= "logout" >退出登录 </button v- if = "islogged" @click= "logout" ></button v- if = "!islogged" @click= "login" ></div> </template> <script> export default { data() { return { isLogged: false , }; }, methods: { login() { uni.login({ provider: & #39;weixin', success: (res) => { // 调用后端接口进行登录验证 // 登录成功后,设置 isLogged 为 true this .isLogged = true ; this .$emit(& #39;login', userInfo); }, }); }, logout() { // 调用后端接口进行退出登录 // 退出登录成功后,设置 isLogged 为 false this .isLogged = false ; this .$emit(& #39;logout'); }, }, }; </script> |