小程序学习笔记1

122 阅读1分钟

获取用户的头像昵称

使用官方apiwx.getUserProfile获取信息(仅在部分版本可用)

  getuserinfo() {
    //授权获取用户的头像和昵称显示在界面
    wx.getUserProfile({
      desc: '获取信息', //授权原因
      success: (obj) => {
        // 保存用户头像和昵称
        this.setData({
          headurl: obj.userInfo.avatarUrl,
          nickname: obj.userInfo.nickName
        })
        console.log(obj)
      },
      fail(err) {
        console.log(err)
      }
    })
  },

注意this的指向性,可使用箭头函数,也可在外面先获取到this,再在里面使用let _this=this

image.png

image.png

二维码扫描

此功能实现同样需要官方的apiwx.scanCode
可以在回调结果里做一个判断,如果是url格式的就打开此网址

    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        console.log(res)
        if (res.result.includes('http://') || res.result.includes('https://')) {
          this.setData({
            weburl: res.result,
            showweb: true
          })
        }
      }
    })

需要用到web-view标签

<web-view wx:if="{{showweb}}" src="{{weburl}}"></web-view>

PS:页面的跳转使用wx.navigaTo

定位使用apiwx.getLocation,同时需要在app.json加上

  "permission": {
    "scope.userLocation": {
      "desc": "授权定位"
    }
  },

组件的抽取

1.在根目录创建components文件夹,并在此文件夹新建一个文件夹,再右键新建components

image.png

2.在父组件的json文件中注册组件

"shop":"../../components/shop-card",

3.父组件中使用

 <shop wx:for="{{shopList}}" item="{{item}}" class="shop-item"></shop>
 <!-- item是自定义的属性 -->

4.子组件的properties接收传递过来的数据

  properties: {
    item:{
      type:Object,
      value:{}
    }
  },

5.渲染数据

<view class="shop-item">
  <image mode="widthFix" src="{{item.img}}" class="shop-img"></image>
  <view class="shop-detail">
    <view style="font-size: 12px;">{{item.name}}</view>
    <view>{{item.point}}积分兑换</view>
  </view>
</view>

效果如图:

image.png