微信小程序项目

创建项目

使用微信开发工具,创建微信小程序项目,注意 AppID ,如果使用测试号,则不能直接上传上线。

  • AppID 在微信开放平台中查找,开发->开发设置->AppID
  • 创建的项目,不选择云开发(云开发指额外提供一些后端和运维的能力)

创建 page 页面

创建的小程序默认有一些文件,根目录有一个 pages 文件夹,这里是存放路由页面的。

右键 -> 新建文件夹 -> 名称为goods -> 新建 pages 页面,会创建4个文件。

- goods.js  逻辑页面
- goods.json    配置页面
- goods.wxml    结构部分
- goods.wxss    样式部分

在 goods.json 文件中,可以修改当前页面的标题

    {
      "usingComponents": {},
      "navigationBarBackgroundColor": "#00ff00",
      "navigationBarTitleText": "购物车"
    }

设置 tabBar

在根目录的 app.json 文件中,添加一个 tabBar,可以做为导航。

  • list 项是数组,最少2个,最多5个。
  • icon 图标自己在 iconfont 中下载,assets 文件夹自己创建。
    "tabBar": {
        "list": [
            {
                "iconPath": "assets/icon-test_1.png",
                "selectedIconPath": "assets/icon-test.png",
                "pagePath": "pages/index/index",
                "text": "首页"
            },
            {
                "iconPath": "assets/icon-test_1.png",
                "selectedIconPath": "assets/icon-test.png",
                "pagePath": "pages/goods/index",
                "text": "商品"
            }
        ]
    }      

商品页面

先使用 json-server 模拟一些商品数据。

json-server -w -p 3000 db.json -s images

然后开放本地请求响应的权限:微信开发工具(右上角)-> 详情 -> 本地设置 -> 不校验合法域名(选中)

请求响应

找到 goods 页面的 onload 生命周期钩子函数,在其中发起请求

    data: {
        arr : []
    },
    onLoad: function (options) {  
        wx.request({
            url: 'http://localhost:3000/goods',
            success : (res)=>{
                //console.log(res.data);
                // 将得到的响应结果,更新到当前页面的 data 中,setData 执行后,页面会自动刷新
                this.setData({
                    arr : res.data
                })
            }
        })
    }
渲染视图

在 pages/goods/goods.wxml 中编写视图

  • wx:for 循环时,index 和 item 是两个关键字,可以直接使用。
    <view wx:for="{{arr}}" wx:key="index">
      <image src="{{'http://localhost:3000/'+item.img}}" />
    
      <view class="btns">
        <view class="btn1"><text>{{item.title}}</text></view>
        <view class="btn2"><button>详情</button></view>
        <view class="btn3"><button>添加到购物车</button></view>
      </view>
    </view>
css控制按钮显示在一行

在 pages/goods/goods.wxss 中编写样式

    .btns{
        display: flex;
        padding: 20rpx;
    }
    
    .btns button{
        display: initial;
        padding: 10rpx;
    }

iPhone6 1rpx = 0.5px 1px = 2rpx
公共数据

在根目录下有一个 app.js 页面

    App({
        baseurl: 'http://localhost:3000/'
    })

在 pages/goods/goods.js 页面中

    const app = getApp();
    
    Page({
        data: {
            arr : [],
            baseurl: app.baseurl
        },
        onLoad: function (options) {
            wx.request({
                url: app.baseurl+'goods',
                success : (res)=>{
                    this.setData({
                        arr : res.data
                    })
                }
            })
        },
    }  

在 pages/goods/goods.wxml 页面的循环中:
    <image src="{{baseurl+item.img}}" />
    <button data-abc="{{item}}" bindtap="add">添加到购物车</button>
绑定事件和参数传递

给按钮绑定触碰事件,事件名称是bindtap,关联的函数是add。

    <button data-abc="{{item}}" bindtap="add">添加到购物车</button>
    Page({
        // data: ...,
        add(event){
            var item = event.target.dataset.abc;
            console.log('item:', item)
        }
    }

微信小程序中,函数的参数需要通过自定义属性来处理,data-abc就是自定义属性的写法,通过dataset可以获取到。

将商品添加到购物车的逻辑

src/app.js

    App({
        goods:[]  // 描述购物车中的所有的商品
    })

src/pages/goods.js

   add(event){
        var item = event.target.dataset.abc;
        // 判断商品是否已经存在,如果存在则数量+1,如果不存在则直接添加
        var index = app.goods.findIndex(g=>g.id===item.id)
        if( index === -1 ){
            app.goods.push({...item, num:1})
        }else{
            app.goods[index].num++;
        }
        // 提示框
        wx.showToast({
            title: '商品添加成功',
            icon: 'success',
            duration: 2000
        })
    }

购物车页面
src/pages/buycar/buycar.js

    const app = getApp();
    
    Page({
        data: {
            arr : [],
            baseurl : app.baseurl
        },
        // 每次显示该页面时,都会触发onShow函数
        onShow: function () {
            this.setData({
                arr: app.goods
            })
        }
    })

src/pages/buycar/buycar.wxml
  <view wx:for="{{arr}}" wx:key="index">
        <image src="{{baseurl+item.img}}" />
        {{item.title}}
        <view class="btns">
            <view><button>-</button></view>
            <view>{{item.num}}</view>
            <view><button>+</button></view>
        </view>
    </view>
购物车页面商品数量的更新
src/pages/buycar/buycar.wxml

    <view><button bindtap="jian" data-abc="{{item}}">-</button></view>
    <view>{{item.num}}</view>
    <view><button bindtap="jia" data-abc="{{item}}">+</button></view>

src/pages/buycar/buycar.js

    jian(e){
        var item = e.target.dataset.abc;
        var index = app.goods.findIndex(obj=>obj.id===item.id);
        app.goods[index].num--;
        if (app.goods[index].num === 0){
            // 删除
            app.goods.splice(index, 1);
        }
        // 更新自身页面
        this.setData({
            arr: app.goods
        })
    },
    jia(e) {
        var item = e.target.dataset.abc;
        var index = app.goods.findIndex(obj => obj.id === item.id);
        app.goods[index].num++;
        // 更新自身页面
        this.setData({
            arr: app.goods
        })
    }

本地数据持久化
设置storage
    wx.setStorage({
        key,
        data
    })

获取storage
    wx.getStorageSync(key)
微信开放能力 – 获取微信账户信息
方法1: 通过js获取微信账户信息

https://developers.weixin.qq.com/miniprogram/dev/api/open-api/user-info/wx.getUserInfo.html

    data: {
        nick: ''
    },
    onShow: function () {
        wx.getUserInfo({
            success:  (res)=>{
                console.log(res.userInfo)
                this.setData({
                    nick: res.userInfo.nickName
                })
            }
        })
    }
方法2: 通过组件获取微信账户信息

https://developers.weixin.qq.com/miniprogram/dev/component/open-data.html

    <open-data type="userNickName"></open-data>

拍照片

https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html

    <button bindtap="paizhao">拍照</button>
    <image src="{{paizhaopian}}" />
   data: {
        paizhaopian:''
    },
    
    paizhao(){
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
            success:  (res)=>{
                // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
                var tempFilePaths = res.tempFilePaths
                console.log(res);
                this.setData({
                    paizhaopian: tempFilePaths[0]
                })
            }
        })
    },

地图

https://developers.weixin.qq.com/miniprogram/dev/component/map.html

https://developers.weixin.qq.com/miniprogram/dev/api/media/map/wx.createMapContext.html

https://developers.weixin.qq.com/miniprogram/dev/api/location/wx.chooseLocation.html

    <button bindtap="fn1">设置收货地址</button>
    
    {{ map.address }}
    
    <map
        style="width:100%;height:400rpx"
        latitude="{{map.latitude}}"
        longitude="{{map.longitude}}"
        markers="{{[{latitude:map.latitude,longitude:map.longitude}]}}"
    >
    </map>

   data: {
        map : null
    },
    fn1(){
        // 打开地图,默认为手机当前位置,可以选择位置,确定后得到当前选择的地址。
        wx.chooseLocation({
            success:(res)=>{
                console.log(res)
                // 本地存储
                wx.setStorageSync('map', res);
                // 提示框
                wx.showToast({
                    title: '收货地址设置成功',
                })
            }
        })
    },
    onShow: function () {
        var obj = wx.getStorageSync('map');
        this.setData({
            map : obj
        })
    },

扫描二维码

先去草料 https://cli.im/ 准备个二维码。

https://developers.weixin.qq.com/miniprogram/dev/api/device/scan/wx.scanCode.html

    wx.scanCode({
        success(res) {
            console.log(res)
            // 识别出图片中的网址后,应该用wx.request发请求,拿响应。
        }
    })

路由(列表页跳转到详情页)
列表页
    <button data-abc="{{item}}" bindtap="fn1">详情</button>
    fn1(e){
        var item = e.target.dataset.abc;
        //console.log(item)
        wx.navigateTo({
            url: '/pages/detail/detail?id='+item.id
        })
    },

详情页
   onLoad: function (options) {
        var id = options.id
        wx.request({
            url: app.baseurl+'goods?id='+id,
            success: (res)=>{
                console.log(res);
                
                this.setData({
                    title : res.data[0].title,
                    img: app.baseurl +res.data[0].img
                })
            }
        })
    }

    <text>{{title}}</text>
    <image src="{{img}}" />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

blueSky-fan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值