自定义组件
在根目录上创建文件夹:components-->mycom-->新建compontent
mycom.json
{
"component": true,// component一定要声明为true
"usingComponents": {}
}
mycom.wxml
<text>{{somebody}} is sb</text>
<view>{{name}}</view>
mycom.js
/**
* 组件的属性列表
*/
properties: {
somebody:{
type:String,
value:"jason"//这个是默认值 页面要是赋值了就用 没有就用这个默认值
}
},
/**
* 组件的初始数据
*/
data: {
name:"tank"
},
应用组件 pages est est.json
{
"usingComponents": {
"mycom":"/components/mycom/mycom"
}
}
pages est est.wxml
<mycom somebody="egon"></mycom>
组件将事件传给页面
mycom.wxml
<button bindtap="click" data-age="1">组件里的按钮</button>
mycom.js
methods: {
click:function(e){
console.log(e.currentTarget.dataset.age)
this.triggerEvent("tt", { "age": e.currentTarget.dataset.age})
}
}
页面test.wxml
<mycom somebody="egon" bind:tt="jia"></mycom>
页面 test.js
jia:function(e){
console.log(e.detail)//取参数
this.setData({
num1:this.data.num1+e.detail.age
})
},
小程序路由跳转
wx.switchTab
只能跳转tabBar页面,不能跳转非tabBar页面
test.wxml
<button bindtap="tiao">跳转连接</button>
test.js
tiao:function(){
wx.switchTab({
url: '/pages/index/index',
})
},
wx.reLaunch
关闭所有页面,打开到应用内的某个页面
test.js
tiao:function(){
wx.reLaunch({
url: '/pages/test2/test2?name=sb',
})
test2.js
onLoad: function (options) {
console.log("test2",options)
},
wx.redirectTo
关闭当前页面,跳转到tabBar页面
test.js
tiao:function(){
wx.redirectTo({
url: '/pages/test2/test2',
})
wx.navigateTo
保留当前页面,跳转tabBar页面 使用wx.navigateBack可以返回原页面 最多十层
test,js
tiao:function(){
wx.navigateTo({
url: '/pages/test2/test2',
})
wx.navigateBack
关闭当前页面 返回上一层页面 通过getCurrentPages()获取页面栈数
tiao: function () {
wx.navigateTo({
url: "/pages/test2/test2"
})
}
tiao: function () {
wx.navigateTo({
url: "/pages/test3/test3"
})
}
tiao: function () {
console.log(getCurrentPages())
wx.navigateBack({
delta: 2,
})
}
navigator
test.wxml
<navigator url="/pages/test3/test3">跳转到新页面</navigator>
小程序本地数据存储
test.wxml
<button bind:tap="cun" >存</button>
test.js
cun:function(){
wx.setStorageSync("heihei", "is sb")//存 同步 setStorage是异步的
console.log(wx.getStorageSync("heihei"))//取
wx.removeStorageSync("heihei")//指定删
wx.clearStorageSync()//全删
},
wx.request请求
test.wxml
<button bind:tap="qing">请求</button>
test.js
qing:function(){
wx.request({
url: 'http://127.0.0.1:8000/test/',
data:{
name: "tank",
like: "piao"
},
method:"POST",
header:{"content-type":"application/json"},
success(res){
console.log(res)//返回后台传来的信息
}
})
},
test.py
from rest_framework.views import APIView
from rest_framework.response import Response
class Test(APIView):
def post(self,request):
param=request.data #前台传来的数据
print(param)
return Response({"code":200,"msg":"ojbk"})
手动完成小程序的登入
前台 app.js
//app.js
App({
onLaunch: function () {
// 展示本地存储能力
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
// 登录
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
console.log(res)
if (res.code){
//发送网络请求
wx.request({
url: 'http://127.0.0.1:8000/login/',
data:{
code:res.code
},
method:"POST",
success(e){
wx.setStorageSync('token', e.data.data.token)
}
})
}
}
})
// 获取用户信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
wx.getUserInfo({
success: res => {
// 可以将 res 发送给后台解码出 unionId
this.globalData.userInfo = res.userInfo
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})
},
globalData: {
userInfo: null
}
})
后台
路由
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r"^test/",test.Test.as_view()),
url(r"^login/",user.Login.as_view()),
]
user.py
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.cache import cache
from app01.wx import WxLogin
import hashlib,time
from app01 import models
class Login(APIView):
def post(self,request):
param=request.data
if param.get('code'):
data=WxLogin.get_openid(param.get("code"))
if data:
val = data['openid'] + "&" + data['session_key']
md5 = hashlib.md5()
md5.update(str(time.clock()).encode("utf-8"))
md5.update(data['session_key'].encode("utf-8"))
key = md5.hexdigest()
cache.set(key, val)
has_user = models.Wxuser.objects.filter(openid=data['openid']).first()
if not has_user:
models.Wxuser.objects.create(openid=data['openid'])
return Response({"code": 200, "msg": "ok", "data": {"token": key}})
else:
return Response({"code": 201, "msg": "无效的code"})
else:
return Response({"code": 202, "msg": "缺少参数"})
WxLogin.py
from app01.wx import settings
import requests
def get_openid(code):
code2Session = "https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code"
response = requests.get(code2Session.format(settings.AppId,settings.AppSecret,code))
data = response.json()
if data.get("session_key"):
print("data",data)
return data
else:
return False
wx-->setting
AppId="wx39a699d0f61b13ae"
AppSecret="d00c23ad3faf96ca218c20f6aaece7a7"
pay_mchid ='1415981402'
pay_apikey = 'xi34nu5jn7x2uujd8u4jiijd2u5d6j8e'
setting
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'python12',
'USER':'root',
'PASSWORD':'',
'HOST':'127.0.0.1',
'PORT': 3306,
# 'OPTIONS': {'charset': 'utf8mb4'},
}
}
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379',
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"PASSWORD": "",
},
},
}