获取 用户头像等信息
<button type="primary" bindtap="getUser">获取用户信息</button>
getUser() {
var that = this;
wx.getUserProfile({
desc: '需要获取您的昵称',
success: res => {
console.log(res);
}
})
},
微信扫码功能
<text bindtap="scanCodeEvent">{{scanCode}}</text>
scanCodeEvent: function () {
var that = this;
wx.scanCode({
onlyFromCamera: true, // 只允许从相机扫码
success(res) {
console.log("扫码成功:" + JSON.stringify(res))
// 扫码成功后 在此处理接下来的逻辑
that.setData({
scanCode: res.result
})
}
})
},
朋友圈分享以及分享朋友带参数获取
onShareAppMessage: function () {
return {
title: '分享并且带参数',
path: 'pages/category/index?jobInfoId=' + 6666, }
},
onShareTimeline: function() {
return {
title: '分享并且带参数',
query: 'userId='+Constant.userId+'&storeId='+Constant.curStoreId+'&share=true',
}
}
微信小程序调起拨打电话功能
<button type="default" bindtap="Tel" data-tel="{{tel}}">拨打电话:{{tel}}</button>
Tel (e) {
var tel = e.currentTarget.dataset.tel;
wx.makePhoneCall({
phoneNumber: tel,
success: function () {
console.log("拨号成功!")
},
fail: function () {
console.log("拨号失败!")
}
})
},
视频付费功能
<video id='myVideo' videoContext controls src='{{src}}' bindtimeupdate="time"></video>
time(e) {
let time = e.detail.currentTime.toFixed(0);
if (time == 10) {
wx.createVideoContext('myVideo').pause();
到时间写逻辑
}
},
微信小程序图片预览
<view class='index_showpic'>
<view class='li_pic' wx:for="{{imgArr}}" wx:key='index'>
<image src='{{item}}' bindtap='previewImg' data-src='{{item}}' class='img'></image>
</view>
</view>
imgArr:[
'http://bpic.588ku.com/element_origin_min_pic/16/10/30/528aa13209e86d5d9839890967a6b9c1.jpg',
'http://bpic.588ku.com/element_origin_min_pic/16/10/30/54fcef525fa8f6037d180f3c26f3be65.jpg',
'http://bpic.588ku.com/element_origin_min_pic/16/10/30/62e3ca3a02dddb002eff00482078d194.jpg',
'http://bpic.588ku.com/element_origin_min_pic/16/10/31/c7167fcfb4ebcd12621c05b0c852e98e.jpg'
]
previewImg:function(e){
var imgUrl = e.currentTarget.dataset.src; //获取当前点击的图片
var imgArr = this.data.imgArr;
console.log(imgUrl,imgArr);
wx.previewImage({
current: imgUrl, //当前图片地址
urls: imgArr, //所有要预览的图片的地址集合数组形式
urls: [imgUrl], //一张图写法
success: function(res) {},
fail: function(res) {},
complete: function(res) {},
})
},
微信小程序视频预览
<video id='myVideo' videoContext controls src='{{src}}' bindtimeupdate="time" bindtap="previewVideo" data-current="{{src}}"></video>
previewVideo(e){
console.log(e.currentTarget.dataset);
wx.previewMedia({
sources: [{
url: e.currentTarget.dataset.current, //视频播放路径
type: 'video',//video视频 image图片
}]
})
},
微信获取位置以及附近的信息
<view wx:if="{{addListShow}}">
<view class="top">
<view class="search-box {{addListShow?'search-box1':''}}">
<view class="region">{{currentRegion.district}}</view>
<view class="shu"></view>
<input bindinput="getsuggest" placeholder="请输入您的店铺地址"></input>
</view>
</view>
<!--关键词输入提示列表渲染-->
<view class="add-list-box">
<scroll-view class="add-list" scroll-y>
<view class="add-item" wx:for="{{suggestion}}" wx:key="index">
<!--绑定回填事件-->
<view bindtap="backfill" id="{{index}}" data-name="{{item.title}}">
<!--根据需求渲染相应数据-->
<!--渲染地址title-->
<view class="title">{{item.title}}</view>
<!--渲染详细地址-->
<view class="add">{{item.addr}}</view>
</view>
</view>
</scroll-view>
</view>
</view>
<view wx:if="{{!addListShow && !chooseCity}}">
<!--地图容器-->
<map id="myMap"
style="width:100%;height:300px;"
longitude="{{longitude}}"
latitude="{{latitude}}" scale="17" bindregionchange="mapChange">
<cover-view class="top">
<cover-view class="back" bindtap="back1">
<!-- <cover-image src="../../images/back.png"></cover-image> -->
</cover-view>
<cover-view class="search-box">
<cover-view class="region" bindtap="chooseCity">{{currentRegion.district}}</cover-view>
<cover-view class="shu"></cover-view>
<cover-view class="placeholder" bindtap="showAddList">请输入您的店铺地址</cover-view>
</cover-view>
</cover-view>
<cover-view class="map-prompt">您可拖动地图, 标记店铺准确位置</cover-view>
<!-- <cover-image class="current-site-icon" src="../../images/my_marker.png"></cover-image> -->
<cover-view class="reload" bindtap="reload">
<cover-view class="center1">
<cover-view class="center2"></cover-view>
</cover-view>
</cover-view>
</map>
<scroll-view class="near-list" scroll-y>
<!--绑定回填事件-->
<view class="near-item" wx:for="{{nearList}}" wx:key="index">
<view class="current-site iconfont icon-location" wx:if="{{index == selectedId }}"></view>
<!--根据需求渲染相应数据-->
<view bindtap="chooseCenter" id="{{index}}" data-name="{{item.title}}">
<!--渲染地址title-->
<view class="title {{ index == selectedId?'title1':'' }}">{{item.title}}</view>
<!--渲染详细地址-->
<view class="add {{ index == selectedId?'add1':'' }}">{{item.addr}}</view>
</view>
</view>
</scroll-view>
<view class="bottom-box">
<button bindtap="selectedOk">确认地址</button>
</view>
</view>
var QQMapWX = require('../../utils/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({
data: {
addListShow: false,
chooseCity: false,
regionShow: {
province: false,
city: false,
district: true
},
regionData: {},
currentRegion: {
province: '选择城市',
city: '选择城市',
district: '选择城市',
},
currentProvince: '选择城市',
currentCity: '选择城市',
currentDistrict: '选择城市',
latitude: '',
longitude: '',
centerData: {},
nearList: [],
suggestion: [],
selectedId: 0,
defaultKeyword: '房产小区',
keyword: ''
},
onLoad: function () {
let self =this;
self.mapCtx = wx.createMapContext('myMap')
// 实例化API核心类
qqmapsdk = new QQMapWX({
key: 'W57BZ-JDB6X-XPA4H-Z76MI-73FF2-24BT4'
});
wx.showLoading({
title: '加载中'
});
//定位
wx.getLocation({
type: 'wgs84',
success(res) {
const latitude = res.latitude
const longitude = res.longitude
//你地址解析
qqmapsdk.reverseGeocoder({
location: {
latitude: latitude,
longitude: longitude
},
success: function (res) {
self.setData({
latitude: latitude,
longitude: longitude,
currentRegion: res.result.address_component,
keyword: self.data.defaultKeyword
})
self.nearby_search();
},
});
},
fail(err) {
wx.hideLoading({});
wx.showToast({
title: '定位失败',
icon: 'none',
duration: 1500
})
setTimeout(function () {
wx.navigateBack({
delta: 1
})
}, 1500)
}
})
},
mapChange: function (e) {
let self = this;
if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')){
self.mapCtx.getCenterLocation({
success: function (res) {
//console.log(res)
self.setData({
nearList:[],
latitude: res.latitude,
longitude: res.longitude,
})
self.nearby_search();
}
})
}
},
//重新定位
reload: function () {
this.onLoad();
},
//地图标记点
addMarker: function (data) {
var mks = [];
mks.push({ // 获取返回结果,放到mks数组中
title: data.title,
id: data.id,
addr: data.addr,
province: data.province,
city: data.city,
district: data.district,
latitude: data.latitude,
longitude: data.longitude,
iconPath: "/images/my_marker.png", //图标路径
width: 25,
height: 25
})
console.log(333,mks);
this.setData({ //设置markers属性,将搜索结果显示在地图中
markers: mks,
currentRegion: {
province: data.province,
city: data.city,
district: data.district,
}
})
wx.hideLoading({});
},
//点击选择搜索结果
backfill: function (e) {
var id = e.currentTarget.id;
let name = e.currentTarget.dataset.name;
for (var i = 0; i < this.data.suggestion.length; i++) {
if (i == id) {
//console.log(this.data.suggestion[i])
this.setData({
centerData: this.data.suggestion[i],
addListShow: false,
latitude: this.data.suggestion[i].latitude,
longitude: this.data.suggestion[i].longitude
});
this.nearby_search();
return;
//console.log(this.data.centerData)
}
}
},
//点击选择地图下方列表某项
chooseCenter: function (e) {
var id = e.currentTarget.id;
let name = e.currentTarget.dataset.name;
for (var i = 0; i < this.data.nearList.length; i++) {
if (i == id) {
this.setData({
selectedId: id,
centerData: this.data.nearList[i],
latitude: this.data.nearList[i].latitude,
longitude: this.data.nearList[i].longitude,
});
this.addMarker(this.data.nearList[id]);
return;
}
}
},
//显示搜索列表
showAddList: function () {
this.setData({
addListShow: true
})
},
// 根据关键词搜索附近位置
nearby_search: function () {
var self = this;
wx.hideLoading();
wx.showLoading({
title: '加载中'
});
// 调用接口
qqmapsdk.search({
keyword: self.data.keyword, //搜索关键词
//boundary: 'nearby(' + self.data.latitude + ', ' + self.data.longitude + ', 1000, 16)',
location: self.data.latitude + ',' + self.data.longitude,
page_size: 20,
page_index: 1,
success: function (res) { //搜索成功后的回调
//console.log(res.data)
var sug = [];
for (var i = 0; i < res.data.length; i++) {
sug.push({ // 获取返回结果,放到sug数组中
title: res.data[i].title,
id: res.data[i].id,
addr: res.data[i].address,
province: res.data[i].ad_info.province,
city: res.data[i].ad_info.city,
district: res.data[i].ad_info.district,
latitude: res.data[i].location.lat,
longitude: res.data[i].location.lng
});
}
console.log(22222222222,sug);
self.setData({
selectedId: 0,
centerData: sug[0],
nearList: sug,
suggestion: sug
})
self.addMarker(sug[0]);
},
fail: function (res) {
//console.log(res);
},
complete: function (res) {
//console.log(res);
}
});
},
//根据关键词搜索匹配位置
getsuggest: function (e) {
var _this = this;
var keyword = e.detail.value;
_this.setData({
addListShow: true
})
//调用关键词提示接口
qqmapsdk.getSuggestion({
//获取输入框值并设置keyword参数
keyword: keyword, //用户输入的关键词,可设置固定值,如keyword:'KFC'
location: _this.data.latitude + ',' + _this.data.longitude,
page_size: 20,
page_index: 1,
//region:'北京', //设置城市名,限制关键词所示的地域范围,非必填参数
success: function (res) {//搜索成功后的回调
//console.log(res);
var sug = [];
for (var i = 0; i < res.data.length; i++) {
sug.push({ // 获取返回结果,放到sug数组中
title: res.data[i].title,
id: res.data[i].id,
addr: res.data[i].address,
province: res.data[i].province,
city: res.data[i].city,
district: res.data[i].district,
latitude: res.data[i].location.lat,
longitude: res.data[i].location.lng
});
}
_this.setData({ //设置suggestion属性,将关键词搜索结果以列表形式展示
suggestion: sug,
nearList: sug,
keyword: keyword
});
},
fail: function (error) {
//console.error(error);
},
complete: function (res) {
//console.log(res);
}
});
},
//确认选择地址
selectedOk: function () {
console.log(this.data.centerData)
}
})
.top {
width: 100%;
height: 80rpx;
line-height: 80rpx;
position: fixed;
top: 0;
left: 0;
padding: 30rpx 20rpx;
z-index: 999;
overflow: hidden;
}
.back {
width: 80rpx;
height: 80rpx;
line-height: 80rpx;
color: #666;
text-align: center;
background: rgb(255,255,255);
font-size: 50rpx;
border-radius: 50%;
float: left;
}
.back cover-image{
width: 50rpx;
height: 50rpx;
display: inline-block;
margin-top: 15rpx;
}
.search-box {
width: 610rpx;
height: 80rpx;
line-height: 80rpx;
border-radius: 40rpx;
background: rgb(255,255,255);
margin-left: 20rpx;
float: left;
overflow: hidden;
}
.search-box1 {
border: 1px solid #ccc;
border-radius: 10rpx;
background: #eee;
}
.search-box .region {
width: 199rpx;
line-height: 80rpx;
font-size: 30rpx;
color: #282828;
text-align: center;
float: left;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.search-box .shu {
width: 1rpx;
height: 80rpx;
background:#ccc;
float: left;
}
.search-box input {
width: 380rpx;
height: 80rpx;
line-height: 80rpx;
font-size: 30rpx;
color: #282828;
padding: 10rpx 20rpx;
box-sizing: border-box;
float: left;
}
.search-box .placeholder{
width: 380rpx;
height: 80rpx;
line-height: 80rpx;
font-size: 30rpx;
color: #ccc;
padding: 0 20rpx;
box-sizing: border-box;
float: left;
}
.add-list-box {
position: absolute;
width: 100%;
height: 100%;
top: 0;
z-index: 998;
padding-top: 150rpx;
background: #fff;
box-sizing: border-box;
overflow: hidden;
}
.add-list {
width: 100%;
height: 1000rpx;
}
.add-item {
line-height: 40rpx;
padding: 30rpx 50rpx;
text-align: left;
border-top: 1px solid #eee;
}
.add-item .title {
color: #282828;
font-size: 32rpx;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.add-item .add {
color: #707070;
font-size: 24rpx;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.current-site-icon {
width: 50rpx;
height: 50rpx;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
.near-list {
height: 650rpx;
padding-bottom: 100rpx;
box-sizing: border-box;
}
.near-item {
line-height: 40rpx;
padding: 30rpx 50rpx 30rpx 90rpx;
text-align: left;
border-bottom: 1px solid #eee;
position: relative;
}
.current-site {
font-size: 40rpx;
color: #3095F9;
position: absolute;
top: 40rpx;
left: 30rpx;
}
.near-item .title {
color: #282828;
font-size: 32rpx;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.near-item .add {
color: #707070;
font-size: 24rpx;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.near-item .title1 {
color: #3095F9;
}
.near-item .add1 {
color: #3095F9;
}
.bottom-box {
width: 100%;
padding: 20rpx;
background: #fff;
box-sizing: border-box;
position: fixed;
left: 0;
bottom: 0;
z-index: 88;
overflow: hidden;
}
.bottom-box button{
width: 100%;
height: 80rpx;
line-height: 80rpx;
border: none;
background: #3095F9;
color: #fff;
font-size: 36rpx;
}
.region-box {
width: 100%;
height: 100%;
background: #FFF;
position: fixed;
top: 0;
left: 0;
z-index: 1001;
}
.region-box .region-top {
position: relative;
font-size: 40rpx;
color: #282828;
font-weight: bold;
line-height: 100rpx;
text-align: center;
}
.region-box .region-back {
width: 80rpx;
height: 80rpx;
font-size: 50rpx;
text-align: center;
position: absolute;
top: 0;
left: 0;
}
.region-box .region-tabs{
line-height: 60rpx;
font-size: 20rpx;
}
.region-tabs .tab {
min-width: 100rpx;
max-width: 200rpx;
line-height: 40rpx;
font-size: 20rpx;
color: #3095F9;
text-align: center;
border: 1rpx solid #3095F9;
border-radius: 20rpx;
display: inline-block;
margin: 20rpx 0 20rpx 20rpx;
padding: 3rpx 20rpx;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.region-list .region-item{
font-size: 30rpx;
color: #282828;
line-height: 80rpx;
padding: 10rpx 30rpx;
border-top: 1rpx solid #eee;
}
.map-prompt {
width: 420rpx;
height: 60rpx;
line-height: 60rpx;
font-size: 24rpx;
color: #707070;
text-align: center;
background: #fff;
border-radius: 10rpx;
box-shadow: 0 0 10rpx rgba(0,0,0,0.1);
position: absolute;
bottom: 40rpx;
left: 50%;
transform: translate(-50%,0);
}
.reload {
width: 80rpx;
height: 80rpx;
background: #fff;
border-radius: 50%;
box-shadow: 0 0 10rpx rgba(0,0,0,0.1);
position: absolute;
bottom: 30rpx;
right: 30rpx;
}
.reload .center1 {
width: 30rpx;
height: 30rpx;
border: 1rpx solid #3095F9;
border-radius: 50%;
margin: 24rpx auto;
}
.reload .center2 {
width: 25rpx;
height: 25rpx;
background: #3095F9;
border-radius: 50%;
margin: 3rpx auto;
}
判断登录用户code是否有效
wx.checkSession({
success: function(res){
console.log("处于登录态");
},
fail: function(res){
console.log("需要重新登录");
wx.login({})
}
})
微信小程序储存图片到手机
showTip() {
wx.downloadFile({
url:'https://img1.baidu.com/it/u=407852637,3650486136&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500',//图片地址
success: function (res) {
//图片保存到本地
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function (data) {
wx.hideLoading()
wx.showModal({
title: '提示',
content: '您的二维码已保存到相册,赶快识别二维码添加小易进行咨询吧',
showCancel: false,
})
},
fail: function (err) {
if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
// 这边微信做过调整,必须要在按钮中触发,因此需要在弹框回调中进行调用
wx.showModal({
title: '提示',
content: '需要您授权保存相册',
showCancel: false,
success: modalSuccess => {
wx.openSetting({
success(settingdata) {
console.log("settingdata", settingdata)
if (settingdata.authSetting['scope.writePhotosAlbum']) {
wx.showModal({
title: '提示',
content: '获取权限成功,再次点击图片即可保存',
showCancel: false,
})
} else {
wx.showModal({
title: '提示',
content: '获取权限失败,将无法保存到相册哦~',
showCancel: false,
})
}
},
fail(failData) {
console.log("failData", failData)
},
complete(finishData) {
console.log("finishData", finishData)
}
})
}
})
}
},
complete(res) {
wx.hideLoading()
}
})
}
})
},
微信小程序上传图片
<button bindtap="upImg">上传图片</button>
upImg() {
var that = this;
wx.chooseMedia({
count: 1,
success(res) {
console.log(res)
//获取 选择 的第 0 个图片临时地址
var tempFile = res.tempFiles[0].tempFilePath;
//执行上传操作
wx.uploadFile({
filePath: tempFile,
name: 'file',
url: 'http://dida100.com/ajax/file.php',
success: res => {
console.log("@@@", res);
console.log("为转换前", res.data)
//转化为js对象
var data = JSON.parse(res.data)
console.log("转换后", data)
//更新图片信息
that.setData({
pic: "http://dida100.com" + data.pic
})
}
})
}
})
},
微信小程序获取手机信息
wx.getSystemInfo({
success(res) {
console.log(res)
}
})
微信小程序获取系统信息
wx.getSystemInfoAsync({
success (res) {
console.log(res.model)
console.log(res.pixelRatio)
console.log(res.windowWidth)
console.log(res.windowHeight)
console.log(res.language)
console.log(res.version)
console.log(res.platform)
}
})
显示消息提示框: wx.showToast()
wx.showToast({
title: '成功',
icon: 'success',
duration: 2000
})
显示消息加载框: wx.showLoading()
wx.showLoading({
title: '加载中',
})
setTimeout(function () {
wx.hideLoading()
}, 2000)
显示模态对话框 wx.showModal
wx.showModal({
title: '提示',
content: '这是一个模态弹窗',
success (res) {
if (res.confirm) {
console.log('用户点击确定')
} else if (res.cancel) {
console.log('用户点击取消')
}
}
})
接口请求 wx.request
wx.request({
url: '',
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json' // 默认值
},
success (res) {
console.log(res.data)
}
})
文件上传 wx.uploadFile
wx.uploadFile({
url: '',
filePath: tempFilePaths[0],
name: 'file',
formData: {
'user': 'test'
},
success (res){
const data = res.data
//do something
}
})
分享朋友圈 onShareTimeline
Page({
/**
* 生命周期函数--监听页面加载
*/
onLoad() {
// 用户点击右上角分享给好友,要先在分享好友这里设置menus的两个参数,才可以分享朋友圈
wx.showShareMenu({
menus: ['shareAppMessage', 'shareTimeline'] //shareAppMessage必须得有
})
},
//用户点击右上角分享朋友圈
onShareTimeline() {
return {
title: '自定义分享标题',
query: "id=110101&name=heyzqt",
imageUrl: ""
}
}
})
调用 wx.login() 方法获取登录登录凭证 code,code 有效期五分钟。
wx.login({
success: (res)=>{
if(res.code){
wx.request({
// 2. 调用后端接口,传入 code
url: 'https://example.com/onLogin',
data: {
code: res.code,
},
// 3. 后端调用 auth.code2Session 接口,换取用户唯一标识 OpenID 、 用户在微信开放平台帐号下的唯一标识 UnionID(若当前小程序已绑定到微信开放平台帐号) 和 会话密钥 session_key 等,将 OpenID 和 UnionID 返回给前端
success (res) {
console.log(res.data)
},
})
}
}
支付wx.requestPayment()
goPay() { // 支付
const openId = wx.getStorageSync("code") // 获取微信的code作为open ID传到后台
console.log(openId)
// payType后台规定的支付方式,orderId 订单id
http.postRequest('调后台的支付接口', { payType: 2, orderId: this.data.detail.id, code: openId },
(res) => {
if (res && res.code == 1) {
var _r = res.data
wx.requestPayment({ //调起支付
'timeStamp': _r.timeStamp,
'nonceStr': _r.nonceStr,
'package': _r.packageValue,
'signType': _r.signType,
'paySign': _r.paySign,
'success': function (res) { // 接口调用成功的回调函数
console.log(res);
//TODO 跳转订单
wx.navigateTo({
url: '/pages/myOrder/myOrder?type=1&list=2',
})
},
'fail': function (res) { // 接口调用失败的回调函数
console.log('fail:' + JSON.stringify(res));
}
})
}
},
(err) => {
console.log(err);
});
},
获取小程序Appid
const accountInfo = wx.getAccountInfoSync()
console.log(accountInfo.miniProgram);
跳转其他小程序
wx.navigateToMiniProgram({
appId: 'wx62dc561909e73cc7',
path: 'page/index/index?id=123',
extraData: {
foo: 'bar'
},
envVersion: 'develop',
success(res) {
// 打开成功
}
})
导航
wx.switchTab() 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面:
wx.switchTab():跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。
wx.reLaunch() 关闭所有页面,打开到应用内的某个页面:
wx.reLaunch():关闭所有页面,打开到应用内的某个页面。
wx.redirectTo() 关闭当前页面,跳转到应用内的某个页面,但是不允许跳转到 tabbar 页面:
wx.redirectTo():关闭当前页面,跳转到应用内的某个页面,但是不允许跳转到 tabbar 页面。
wx.navigateTo() 保留当前页面,跳转到应用内的某个页面,但是不能跳到 tabbar 页面:
wx.navigateTo():保留当前页面,跳转到应用内的某个页面,但是不能跳到 tabbar 页面。
wx.navigateBack() 关闭当前页面,返回上一页面或多级页面:
wx.navigateBack():关闭当前页面,返回上一页面或多级页面。
缓存
wx.setStorageSync(key, value) 将数据同步存储在本地缓存指定的 key 中:
wx.setStorageSync(key, value):将数据同步存储在本地缓存指定的 key 中。
wx.getStorageSync(key) 从本地缓存中同步获取指定 key 的内容:
wx.getStorageSync(key):从本地缓存中同步获取指定 key 的内容。
removeStorageSync(key) 从本地缓存中同步移除指定 key:
removeStorageSync(key):从本地缓存中同步移除指定 key。
wx.clearStorageSync() 同步清理本地全部的数据缓存:
wx.clearStorageSync():同步清理本地全部的数据缓存。
wx.batchSetStorageSync([{key, value}]) 将数据同步批量存储在本地缓存中指定的 key 中:
wx.batchSetStorageSync([{key, value}]):将数据同步批量存储在本地缓存中指定的 key 中。
wx.batchGetStorageSync([key]) 从本地缓存中同步批量获取指定 key 的内容:
wx.batchGetStorageSync([key]):从本地缓存中同步批量获取指定 key 的内容。
图片预览
<view class="container">
<view class="area-middle" bindtap="gocommentDetail">
<text>这件商品真的是挺好的</text>
<view class="comimg-box">
<image src="{{item}}" data-src="{{item}}" data-list="{{imgArr}}" wx:for="{{imgArr}}" catchtap="pictureview" wx:key="index" ></image>
</view>
</view>
</view>
imgArr: [
'https://xyylcdn.weein.cn/group1/M00/06/BF/rBUgBF8WtdWAKPOrAABgCedJ7gk388.jpg',
'https://xyylcdn.weein.cn/group1/M00/06/BF/rBUgBF8WtyuASPvRAABkG1TAPl8877.jpg',
'https://xyylcdn.weein.cn/group1/M00/04/19/rBUUDl78bAyAUgpEAAMr1h87H1A753.jpg'
],
pictureview: function (event) {
var src = event.currentTarget.dataset.src; //获取data-src
var imgList = event.currentTarget.dataset.list; //获取data-list
wx.previewImage({
current: src, // 当前显示图片的http链接
urls: imgList // 需要预览的图片http链接列表
})
},
调取相册以及相机
<button type="primary" bindtap="acquire">调取相册以及相机</button>
acquire () {
console.log(111);
wx.chooseMedia({
count: 9,//上传限制,最大9个
mediaType: ['image','video'],//image只能拍摄图片或从相册选择图片,video只能拍摄视频或从相册选择视频,mix可同时选择图片和视频
sourceType: ['album', 'camera'],//album 从相册选择,camera 使用相机拍摄
maxDuration: 30,//拍摄视频最长拍摄时间,单位秒。时间范围为 3s 至 60s 之间。不限制相册
camera: 'back',//back 使用后置摄像头,front 使用前置摄像头
success(res) {
console.log(res.tempFiles[0].tempFilePath)
console.log(res.tempFiles[0].size)
}
})
},
小程序获取位置
<view class="container">
<button bindtap='getLocation'>获取位置</button>
<view wx:if="{{latitude !=''}}">
<view>纬度:{{latitude}}</view>
<view>经度:{{longitude}}</view>
<view>速度:{{speed}}</view>
<view>位置的精确度:{{accuracy}}</view>
<view>高度:{{altitude}}</view>
<view>垂直精度:{{accuracy}}</view>
<view>水平精度:{{accuracy}}</view>
</view>
</view>
在根目录app.json配置
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示"
}
},
//获取应用实例
const app = getApp()
Page({
data: {
latitude: '',
longitude: '',
speed: '',
accuracy: '',
altitude: '',
verticalAccuracy: '',
horizontalAccuracy: ''
},
getLocation: function () {
var _this = this;
wx.getLocation({
type: 'wgs84',
altitude: true,//传入 true 会返回高度信息,由于获取高度需要较高精确度,会减慢接口返回速度。传入false就把altitude属性删掉
success: function (res) {
console.log(res);
var latitude = res.latitude
var longitude = res.longitude
var speed = res.speed
var accuracy = res.accuracy
var altitude = res.altitude
var verticalAccuracy = res.verticalAccuracy
var horizontalAccuracy = res.horizontalAccuracy
_this.setData({
latitude: latitude,
longitude: longitude,
speed: speed,
accuracy: accuracy,
altitude: altitude,
verticalAccuracy: verticalAccuracy,
horizontalAccuracy: horizontalAccuracy
})
},
complete :function(r){
console.log(r)
console.log(222)
}
})
}
})
可以在初始化的时候在onshow调用设置接口
如果用户拒绝了授权,在上述方法添加用户失败回调
fail: () => {
//不允许打开定位
wx.getSetting({
success: (res) => {
console.log(222,res);
if (!res.authSetting['scope.userLocation']) {
//打开提示框,提示前往设置页面
this.setData({
layerModel: true
})
}
}
})
}
下次进入根据回调状态判断是否授权
<button open-type='openSetting' bindopensetting="openSetting">重新定位</button>
弹窗打开引导授权管理,重新授权
openSetting(e) {//跳转授权设置之后的回调
if (e.detail.authSetting['scope.userLocation']) { //此处同上同理
wx.getLocation({
type: 'wgs84',
success(res) {
const latitude = res.latitude
const longitude = res.longitude
const speed = res.speed
const accuracy = res.accuracy
}
})
}
},
***git操作***
git branch 查看本地所有分支
git status 查看当前状态
git commit 提交
git branch -a 查看所有的分支
git branch -r 查看远程所有分支
git commit -am "init" 提交并且加注释
git remote add origin git@192.168.1.119:ndshow
git push origin master 将文件给推到服务器上
git remote show origin 显示远程库origin里的资源
git push origin master:develop
git push origin master:hb-dev 将本地库与服务器上的库进行关联
git checkout --track origin/dev 切换到远程dev分支
git branch -D master develop 删除本地库develop
git checkout -b dev 建立一个新的本地分支dev
git merge origin/dev 将分支dev与当前分支进行合并
git checkout dev 切换到本地dev分支
git remote show 查看远程库
git add .
git rm 文件名(包括路径) 从git中删除指定文件
git clone git://github.com/schacon/grit.git 从服务器上将代码给拉下来
git config --list 看所有用户
git ls-files 看已经被提交的
git rm [file name] 删除一个文件
git commit -a 提交当前repos的所有的改变
git add [file name] 添加一个文件到git index
git commit -v 当你用-v参数的时候可以看commit的差异
git commit -m "This is the message describing the commit" 添加commit信息
git commit -a -a是代表add,把所有的change加到git index里然后再commit
git commit -a -v 一般提交命令
git log 看你commit的日志
git diff 查看尚未暂存的更新
git rm a.a 移除文件(从暂存区和工作区中删除)
git rm --cached a.a 移除文件(只从暂存区中删除)
git commit -m "remove" 移除文件(从Git中删除)
git rm -f a.a 强行移除修改后文件(从暂存区和工作区中删除)
git diff --cached 或 $ git diff --staged 查看尚未提交的更新
git stash push 将文件给push到一个临时空间中
git stash pop 将文件从临时空间pop下来
微信小程序基础使用方法
"navigationStyle":"custom" 不使用原生导航
H5页面使用百度AK获取定位
public/index配置
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=RinMYF4uDF8OHWTwpwsiwNpFqMaTpqeB"></script>
封装获取定位Promise方法
let getCurrentCityName = function () {
return new Promise(function (resolve, reject) {
let myCity = new BMap.LocalCity()
myCity.get(function (result) {
resolve(result.name)
})
})
}
export default getCurrentCityName
在vue页面引入使用 vue-amap
import getCurrentCityName from './positioning'
positionCity() {
getCurrentCityName().then((city) =>{
console.log(22222222,city);
this.city = city
});
},
自定义按钮级别权限
//自定义·全局方法按钮级别权限,先获取本地权限数据 permissions
//先获取本地权限数据 permissions
// let btnPermission = (data) => {
// let permissions = JSON.parse(localStorage.getItem('permissions '));
// let isHave = permissions.includes(data);
// return isHave;
// }
// export default btnPermission;
// 通过自定义指令判断按钮权限
//先获取本地权限数据 permissions
let has = {
install(Vue){
Vue.directive('has',{
bind(el,binding,vnode){
let {value} = binding;
//判断是否有权限
let permissions = JSON.parse(localStorage.getItem('permissions'));
console.log(permissions);
let hasBtn = permissions.includes(value);
//没有权限则删除父元素,或者隐藏当前元素
if (!hasBtn) {
if (!el.parentNode) {
el.style.display = 'none'
} else {
el.parentNode.removeChild(el)
}
}
}
})
}
}
export default has;
使用 v-if='$has('add')'
//挂载自定义按钮权限指令
import has from '@/utils/directive';
Vue.use(has);
过滤属性,传递类型
export function statusFilter(status) {
const statusMap = {
1: '已发布',
9: '已删除',
0: '草稿'
}
return statusMap[status]
}
比较两个对象是否一致
export function isObjEqual(o1,o2){
let num1 =JSON.parse(JSON.stringify(o1))
let num2 =JSON.parse(JSON.stringify(o2))
delete num1.type
delete num2.type
console.log(num1,num2);
var props1 = Object.getOwnPropertyNames(num1);
var props2 = Object.getOwnPropertyNames(num2);
if (props1.length != props2.length) {
return false;
}
for (var i = 0,max = props1.length; i < max; i++) {
var propName = props1[i];
if (o1[propName] !== o2[propName]) {
return false;
}
}
return true;
}
vue+vite项目创建以及api使用
Element嵌套表格
<template>
<div class="dashboard-container">
<el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-table :data="ruleForm.tableList" style="width: 100%">
<el-table-column prop="name" align="center">
<template slot-scope="scope">
<el-form-item label="活动名称" :prop="'tableList.'+scope.$index+'.name'" :rules='rules.name'>
<el-input v-model="scope.row.name"></el-input>
</el-form-item>
</template>
</el-table-column>
<el-table-column prop="name" align="center">
<template slot-scope="scope">
<el-form-item label="活动名称" :prop="'tableList.'+scope.$index+'.name'" :rules='rules.name'>
<el-input v-model="scope.row.name"></el-input>
</el-form-item>
</template>
</el-table-column>
</el-table>
<el-table-column align="center">
<template>
<el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</template>
</el-table-column>
</el-form>
</div>
</template>
<script>
export default {
data() {
return {
ruleForm: {
tableList: [{
name:""
}],
},
rules: {
name: [
{ required: true, message: '请输入活动名称', trigger: 'blur' },
{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
}
};
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
}
</script>
<style scoped>
</style>
循环from表单加验证
<template>
<div class="personal">
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-row :gutter="35">
<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb20" v-for="(item, index) in ruleForm.list"
:key="index">
<el-form-item :label="item.label" :prop="`list.${index}.name`" :rules="rules.name">
<el-input v-model="item.name"></el-input>
</el-form-item>
</el-col>
</el-row>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
export default {
name: 'personal',
data() {
return {
columns: [{
label: 'Name',
prop: 'name'
}, {
label: 'Address',
prop: 'address'
}],
tableData: [{
name: 'John Brown',
address: 'New York No. 1 Lake Park'
}, {
name: 'Jim Green',
address: 'London No. 1 Lake Park'
},],
ruleForm: {
list: [
{
label: "第一个",
name: "",
},
{
label: "第二个",
name: "",
},
{
label: "第三个",
name: "",
},
],
},
rules: {
name: [
{ required: true, message: '请输入活动名称', trigger: 'blur' },
{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
],
}
};
},
computed: {
},
created() {
},
methods: {
submitForm(formName) {
console.log(this.$refs['ruleForm'].validate((valid, fields) => { }));
this.$refs[formName].validate((valid) => {
if (valid) {
alert('submit!');
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
};
</script>
<style scoped lang="scss">
.personal {}
</style>
输入框回车到第二个输入框
<el-form-item>
<el-input
v-model="searchForm.username"
autocomplete="off"
placeholder="用户名"
@keyup.enter.native="lineFeed"
>
</el-input>
</el-form-item>
<el-form-item>
<el-input
ref="password"
type="password"
v-model="searchForm.userpassword"
autocomplete="off"
placeholder="密码"
></el-input>
</el-form-item>
import {reactive, toRefs,getCurrentInstance} from 'vue'
const { proxy } = getCurrentInstance()
const lineFeed = () => {
proxy.$refs.password.focus();
};
居中
color: #d3d6dd;
width: 1920px;
height: 1080px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
transform-origin: left top;
overflow: hidden;