一、实验目标
1、学习使用快速启动模板创建小程序的方法;2、学习不使用模板手动创建小程序的方法。
二、实验步骤
列出实验的关键步骤、代码解析、截图。
1.安装微信开发者工具并新建项目
2.这时可以看到系统默认的小程序模板
4.在app.json文件window属性将navigationBarBackgroundColor改为"#663399";将navigationBarTitleText改为"手动创建第一个小程序"
5.在pages/index/index.wxml文件中添加图像、文本、按钮三个组件,其中图片和文本分别代表用户头像和昵称,并用src和name变量表示;并在pages/index/index.js文件中Page属性的data中添加src和name的原始来源
6.接下来是逻辑实现:修改button组件的代码,为其添加获取用户信息事件getUserProfile;并在pages/index/index.js文件中添加getUserProfile事件实现
7.在pages/index/index.wxss文件中添加container和图片的格式
8.完整代码如下:
// index.js
// 获取应用实例
const app = getApp()
Page({
data: {
src:'https://pic4.zhimg.com/50/v2-6afa72220d29f045c15217aa6b275808_hd.jpg?source=1940ef5c',
name:'Hello World'
},
// 事件处理函数
bindViewTap() {
wx.navigateTo({
url: '../logs/logs'
})
},
onLoad() {
if (wx.getUserProfile) {
this.setData({
canIUseGetUserProfile: true
})
}
},
getUserProfile(e) {
// 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
wx.getUserProfile({
desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
console.log(res)
let info=res.userInfo;
this.setData({
src:info.avatarUrl,
name:info.nickName
//userInfo: res.userInfo,
//hasUserInfo: true
})
}
})
},
getUserInfo(e) {
// 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息
console.log(e)
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
},
getMyInfo:function(e){
console.log(e.detail.userInfo)
}
})
//index.json
{
"usingComponents": {},
"navigationBarBackgroundColor": "#663399",
"navigationBarTitleText": "手动创建第一个小程序"
}
<!--index.wxml-->
<view class="container">
<image src="{{src}}"mode='widthFix'></image>
<text>{{name}}</text>
<button type="primary" bindtap="getUserProfile">
点击获取头像和昵称
</button>
</view>
/**index.wxss**/
.container{
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-around;
}
image{
/* height: 240px;
width: 120px;*/
width:200rpx;
height:200rpx;
border-radius: 50%;
overflow:hidden;
}
//app.json
{
"pages":[
"pages/index/index"
],
"window":{
"backgroundTextStyle":"light",
"navigationBarBackgroundColor": "#663399",
"navigationBarTitleText": "手动创建第一个小程序",
"navigationBarTextStyle":"black"
},
"style": "v2",
"sitemapLocation": "sitemap.json"
}
/**app.wxss**/
.container {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
padding: 200rpx 0;
box-sizing: border-box;
}
三、程序运行结果
四、问题总结与体会
在本次实验中,我对于小程序的开发有了一些基础的概念,比如该怎么设置组件、以及处理事件等等。