微信小程序之公共组件

it2026-10-04  3

首先我们要创建一个公共组件

然后在login.json文件中将component定义为true

{ "component": true, "usingComponents": {} }

在login.wxml添加内容

<!-- 登录 --> <van-popup show="{{ show }}" position="top" custom-style="height: 60%;" close-on-click-overlay="{{true}}" > <image src="../../image/index/yong.png"></image> <view>授权登录</view> <view>请授权小程序登录</view> <view>我们不会公布您的这些信息</view> <view>只是为了给您提供更好的服务</view> <button open-type="getUserInfo" bindgetuserinfo="GetUserInfo" style="background-color: green;color: white;"> 允许 </button> <button bindtap="GetQuUserInfo"> 暂不登录 </button> </van-popup>

在login.js

Component({ options:{ multipleSlots: true // 在组件定义时的选项中启用多slot支持 }, /** * 组件的属性列表 */ properties: { }, /** * 组件的初始数据 */ data: { show:true, }, /** * 组件的方法列表 */ methods: { GetUserInfo:function(e){ if (e.detail.userInfo) { this.getLogin() this.setData({ show: false }); }else{ //用户按了拒绝按钮 wx.showModal({ title:'警告', content:'您点击了拒绝授权,无法获取您的信息,请授权之后再进入!!!', showCancel:false, confirmText:'返回授权', }) } }, GetQuUserInfo(){ //暂不登录 this.setData({ show: false }); }, getLogin(){ wx.login({ success (res) { wx.request({ url: 'https://api.it120.cc/wangkai/user/wxapp/login', //登录的url data: { code: res.code }, success:function(res){ if(res.data.code==0){ //code为0代表成功 wx.setStorageSync("token",res.data.data.token) } } }) } }) } }, // 组件所在页面的生命周期函数 pageLifetimes: { show: function() { // 页面被展示 var value = wx.getStorageSync('token') if (value) { this.setData({ show: false }); } }, hide: function() { // 页面被隐藏 var value = wx.getStorageSync('token') if (!value) { this.setData({ show: true }); } }, } })

父级页面的.json文件中添加

{ "usingComponents": { "login":"../login/login" } }

在父级页面的.wxml文件中

<login>//这个是json中的名称,"login":"../login/login" <van-popup show="{{ show }}" position="top" custom-style="height: 60%;" close-on-click-overlay="{{true}}" > <image src="../../image/index/yong.png"></image> <view>授权登录</view> <view>请授权小程序登录</view> <view>我们不会公布您的这些信息</view> <view>只是为了给您提供更好的服务</view> <button open-type="getUserInfo" bindgetuserinfo="GetUserInfo" style="background-color: green;color: white;"> 允许 </button> <button bindtap="GetQuUserInfo"> 暂不登录 </button> </van-popup> </login>

在.wxml中显示(样式不好看,可以忽略)

最新回复(0)