【微信小程序】小程序功能开发

【微信小程序】小程序功能开发_第1张图片

文章目录

    • 1. 用户登录
      • 1.1 发送短信
      • 1.2 登录
    • 2. 页面传值
      • 2.1 父页面向子页面传值
      • 2.2 子父页面
    • 3. 腾讯云的对象存储
      • 3.1 快速使用
    • 4. 发布
      • 4.1 发布流程的问题
      • 4.2 组件:进度条
      • 4.3 修改data中的局部数据
      • 4.4 闭包
      • 4.5 小程序
      • 4.6 API
      • 4.7 规则
    • 5.restful api回顾
      • 5.1 APIView ( 可以 )
      • 5.2 ListAPIView
        • 5.2.1 用户传递某些值
        • 5.2.2 fields和exclude的区别?
        • 5.2.3 read_only
        • 5.2.4 复杂需求
        • 5.2.5 serializers嵌套


1. 用户登录

1.1 发送短信

1.2 登录

  • 小程序公共对象

    • app.js

      App({
      
        /**
         * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次)
         */
        onLaunch: function () {
      
        },
        globalData:{
          userInfo: null, 
        }
      })
      
    • 其他页面操作公共值

      var app = getApp();
      Page({
      	data: {
        	},
        	onShow:function(){
        		app.globalData
        	}
      });
      

      注意:修改globalData之后,其他页面以用的值不会自动变化,而是需要手动设置。

  • 本地存储操作

    wx.getStorageSync('userInfo');
    wx.setStorageSync('userInfo',"sdfsfd");
    wx.removeStorageSync("userInfo")
    
  • 页面调用栈

    var pages = getCurrentPages();
    prevPage = pages[pages.length-2];
    
  • 跳转回上一个页面

    wx.navigateBack({});
    
  • 小程序页面的生命周期

    • onLoad(一次)
    • onShow(只要展示这个页面,就会自动加载)
    • onReady(一次)
    • onHide(每次页面隐藏就会自动加载,)
    • onUnload(卸载页面,小程序关闭)
  • 全局app.js

    App({
    
      /**
       * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次)
       */
      onLaunch: function () {
    
      },
      globalData:{
        userInfo: null, 
      }
    })
    
  • wx:if指令

2. 页面传值

2.1 父页面向子页面传值

父页面:

/pages/xx/xxx?id=1

子页面

onLoad:function(option){
	
}

2.2 子父页面

子页面

var pages = getCurrentPages();
var prevPage = pages[pages.length-2];
// prevPage.setData({ topicText:topicInfo.title });

注意:data-xx 可以给事件传值。

3. 腾讯云的对象存储

  • 第一阶段:文件服务器,将文件存储在某个服务器(目录结构的划分)。
  • 第二阶段:
    • 文件存储,将文件存储在某个服务器(目录结构的划分)。
    • 对象存储,优化存储和操作优化(不支持目录结构划分)。
  • 第三阶段:云服务(阿里/腾讯/七牛/亚马逊)
    • 文件存储
    • 对象存储

3.1 快速使用

  • 注册相关信息
  • 开发文档

4. 发布

4.1 发布流程的问题

  • 方式一

    1. 打开图片进行本地预览
    2. 输入文字 & 选择相应的信息
    3. 点击发布按钮
    	3.1 将本地图片上传到 腾讯云对象存储中COS(oss),并将COS中的图片地址返回。
    	3.2 将COS中的图片URL和文字等信息一起提交到后台。
    BUG:
    	在3.2步骤时可能拿不到COS中的图片。
    
    function onClickSubmit(){
        // 耗时1分钟,不会阻塞。
        wx.request({
            url:"...",
            success:function(res){
                console.log(res)
            }
        })
        console.log(123);
    }
    
  • 方式二(推荐)

    1. 打开图片进行本地预览
    2. 将本地图片上传到 腾讯云对象存储中COS
    3. 输入文字 & 选择相应的信息
    4. 发布:
    	必须上传完毕之后,才允许点击发布按钮。
    

4.2 组件:进度条

<progress percent="{{percent1}}"  ></progress>

<progress percent="{{percent2}}" activeColor="#DC143C" ></progress>

4.3 修改data中的局部数据

<view>-----案例------view>
<view>点击按钮完成,将图片1的进度条更新为80%view>
<view wx:for="{{imageList}}">
  <view>{{item.title}}view>
  <progress percent="{{item.percent}}"  >progress>
view>

<button bindtap="changePercent" >点击button>
  data: {
    percent1:20,
    percent2:50,
    imageList:[
      {id:1,title:"图片1",percent:20},
      { id: 1, title: "图片2", percent: 30 },
      { id: 1, title: "图片3", percent: 60 },
    ]
  },
  changePercent:function(){
    // 方式1:错误
    /*
    this.setData({
      imageList[0].person: 80
    });
    */
    
    // 方式2:可以,由于需要全部修改,所以性能差。
    /*
    var dataList = this.data.imageList;
    dataList[0].percent = 80;
    this.setData({
      imageList: dataList
    });
    */
    
    // 方式3:推荐
    var num = 2;
    this.setData({
      ["imageList[0].percent"]:80,
      ["imageList[" + num + "].percent"]: 90,
      ["imageList[1].title"]:"突突突突突"
    })

  },

4.4 闭包

var dataList = ["alex", "changxin", "cck"]
for (var i in dataList) {
  (function(data){
    wx.request({
      url: 'xxxxx',
      success: function (res) {
        console.log(data);
      }
    })
  })(dataList[i])
}

4.5 小程序

  • 选图片

  • 填内容

  • 提交

    {
    	cover:"https://mini-1251317460.cos.ap-chengdu.myqcloud.com/08a9daei1578736867828.png",
    	content:"小程序开发太简单了",
    	address:"北京市",
    	topic:1,
    	images:[
    		"https://mini-1251317460.cos.ap-chengdu.myqcloud.com/08a9daei1578736867828.png",
    		"https://mini-1251317460.cos.ap-chengdu.myqcloud.com/08a9daei1578736867828.png"
    	]
    }
    
    {
    	cover:"https://mini-1251317460.cos.ap-chengdu.myqcloud.com/08a9daei1578736867828.png",
    	content:"小程序开发太简单了",
    	address:"北京市",
    	topic:1,
    	
    	
    	
    	images:[
    		{
    			path:"https://mini-1251317460.cos.ap-chengdu.myqcloud.com/08a9daei1578736867828.png",
    			cos_key:"08a9daei1578736867828.pn"
    		},
    		{
    			path:"https://mini-1251317460.cos.ap-chengdu.myqcloud.com/08a9daei1578736867828.png",
    			cos_key:"08a9daei1578736867828.pn"
    		},
    	]
    }
    

4.6 API

from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from rest_framework import serializers
from apps.api import models
class NewsDetailModelSerializer(serializers.Serializer):
    key = serializers.CharField()
    cos_path = serializers.CharField()
    
class NewsModelSerializer(serializers.ModelSerializer):
    images = NewsDetailModelSerializer(many=True)
    class Meta:
        model = models.News
        fields = "__all__"

class NewsView(CreateAPIView):
    """ 创建动态的API """
    serializer_class = NewsModelSerializer
class News(models.Model):
    """
    动态
    """
    cover = models.CharField(verbose_name='封面', max_length=128)
    content = models.CharField(verbose_name='内容', max_length=255)
    topic = models.ForeignKey(verbose_name='话题', to='Topic', null=True, blank=True)
    address = models.CharField(verbose_name='位置', max_length=128, null=True, blank=True)

    user = models.ForeignKey(verbose_name='发布者', to='UserInfo', related_name='news')

    favor_count = models.PositiveIntegerField(verbose_name='赞数', default=0)

    viewer_count = models.PositiveIntegerField(verbose_name='浏览数', default=0)

    comment_count = models.PositiveIntegerField(verbose_name='评论数', default=0)

    create_date = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

class NewsDetail(models.Model):
    """
    动态详细
    """
    key = models.CharField(verbose_name='腾讯对象存储中的文件名', max_length=128, help_text="用于以后在腾讯对象存储中删除")
    cos_path = models.CharField(verbose_name='腾讯对象存储中图片路径', max_length=128)
    news = models.ForeignKey(verbose_name='动态', to='News')

4.7 规则

{
    k1:v1,
    k2:v2,
    k3:{...},
    k4:[
        {....}
    ]
}

5.restful api回顾

5.1 APIView ( 可以 )

from rest_framework.response import Response
class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserInfo
        fields = "__all__"

class UserView(APIView):

    def get(self,request,*args,**kwargs):
        user_list = models.UserInfo.objects.all()
        ser = UserModelSerializer(instance=user_list,many=True)
        return Response(ser.data)

    def post(self,request,*args,**kwargs):
        ser = UserModelSerializer(data=request.data)
        if ser.is_valid():
            # models.UserInfo.objects.create(**ser.validated_data)
            ser.save(user_id=1)
            return Response(ser.data)
        return Response(ser.errors)

5.2 ListAPIView

ListAPIView,CreateAPIView,RetrieveAPIView,UpdateAPIView,DestroyAPIView
class NewTestModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.News
        fields = "__all__"

class NewTestView(CreateAPIView,ListAPIView):
    serializer_class = NewTestModelSerializer
    queryset = models.News.objects.filter(id__gt=4)

5.2.1 用户传递某些值

创建用户时,自己在后台生成一个UID。

class NewTestModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.News
        fields = "__all__"

class NewTestView(CreateAPIView,ListAPIView):
    serializer_class = NewTestModelSerializer
    queryset = models.News.objects.filter(id__gt=4)

    def perform_create(self, serializer):
        serializer.save(uid=str(uuid.uuid4()))

5.2.2 fields和exclude的区别?

通过fields和exclude定制页面展示数据。

需求:只显示用户表的id,name,age的数据,其他不显示。

class NewTestModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.News
        # fields = ["id","name",'age']
        # fields = "__all__"
        exclude = ['gender']

class NewTestView(ListAPIView):
    serializer_class = NewTestModelSerializer
    queryset = models.User.objects.all()
    
[
    {id:1,name:'xxx',age:18},
    {id:1,name:'xxx',age:11},
    {id:1,name:'xxx',age:99},
]

需求:数据库有5个字段,显示7个字段。

class NewTestModelSerializer(serializers.ModelSerializer):
    xx = serializers.CharField(source='id')
    x1 = serializers.SerializerMethodField()
    class Meta:
        model = models.News
        # fields = "__all__"
        # fields = ['id','name','age','gender','phone','xx','x1']
        exclude = ['id','name']
	
    def get_x1(self,obj):
        return obj.id
    
class NewTestView(ListAPIView):
    serializer_class = NewTestModelSerializer
    queryset = models.User.objects.all()
    
[
    {id:1,name:'xxx',age:18...   xx:1,x1:1},
    {id:2,name:'xxx',age:11...   xx:2,x1:2},
    {id:3,name:'xxx',age:99,     xx:3,x1:3},
]

5.2.3 read_only

添加时不要,查看时候需要。

需求:编写两个接口 添加(3字段)、获取列表(5个字段)

class NewTestModelSerializer(serializers.ModelSerializer):
    # phone = serializers.CharField(source='phone',read_only=True)
    # email = serializers.CharField(source='email',read_only=True)
    class Meta:
        model = models.News
        fields = "__all__"
        read_only_fields = ['phone','email',]
        
class NewTestView(CreateAPIView, ListAPIView):
    serializer_class = NewTestModelSerializer
    queryset = models.User.objects.all()
    
添加:
	{
        name:'xx',
        age:'19',
        gender:1
    }
获取:
	[
        {name:'xx',age:'xx',gender:'',phone:'xx',email:xxx}
    ]

5.2.4 复杂需求

添加时用一个serializers、列表时用一个serializers

class NewTestModelSerializer1(serializers.ModelSerializer):
    class Meta:
        model = models.News
        fields = "__all__"
        
class NewTestModelSerializer2(serializers.ModelSerializer):
    class Meta:
        model = models.News
        fields = "__all__"

class NewTestView(CreateAPIView, ListAPIView):
    queryset = models.User.objects.all()
    
	def get_serializer_class(self):
        if self.request.method == 'POST':
            return NewTestModelSerializer1
        if self.request.method == 'GET':
            return NewTestModelSerializer2

5.2.5 serializers嵌套

class CreateNewsTopicModelSerializer(serializers.Serializer):
    key = serializers.CharField()
    cos_path = serializers.CharField()


class CreateNewsModelSerializer(serializers.ModelSerializer):
    imageList = CreateNewsTopicModelSerializer(many=True)

    class Meta:
        model = models.News
        exclude = ['user', 'viewer_count', 'comment_count',"favor_count"]

    def create(self, validated_data):
        # 把imageList切走
        image_list = validated_data.pop('imageList')

        # 创建New表中的数据
        news_object = models.News.objects.create(**validated_data)

        data_list = models.NewsDetail.objects.bulk_create(
            [models.NewsDetail(**info, news=news_object) for info in image_list]
        )
        news_object.imageList = data_list

        if news_object.topic:
            news_object.topic.count += 1
            news_object.save()

        return news_object

class NewsView(CreateAPIView):
    """
    发布动态
    """
    serializer_class = CreateNewsModelSerializer
    def perform_create(self, serializer):
        # 只能保存:News表中的数据()
        # 调用serializer对象的save(先调用create)
        new_object = serializer.save(user_id=1)
        return new_object

你可能感兴趣的:(【微信小程序】,微信小程序,小程序,微信)