# 小程序动态class

思路:定义一个变量,标签上传递一个data-xxx的变量,点击时修改该变量的值为传递过来的值。

这样class中再通过判断添加active类

<view class="flex p-4">
  <view class="card-item {{hasException==='0' ? 'active' : ''}}" data-has-exception="0" bind:tap="selectTap">无异常</view>
  <view class="card-item {{hasException==='1' ? 'active' : ''}}" data-has-exception="1" bind:tap="selectTap">有异常</view>
</view>

selectTap() {
	const { hasException } = e.target.dataset
  // hasException = '1' 有异常  '0' 无异常
  this.setData({
    hasException: hasException
  })
}
1
2
3
4
5
6
7
8
9
10
11
12

# 动态样式

小程序的属性不支持绑定函数或者computed之类的,并且不能传参。

可以利用wxs模块 (opens new window)来达到相同的效果

export一个返回class类名的函数即可

module.exports = {
  generateColor: function (param) {
    switch (param) {
      case '四级':
        return 'color-grade4'
      case '三级':
        return 'color-grade3'
      case '二级':
        return 'color-grade2'
      case '一级':
        return 'color-grade1'
      default:
        return ''
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# wx.request封装

const config = require('../../config/.env.development')
import qs from 'querystring'
const BASE_URL = config.BASE_URL
/**
 * @description: 发起请求
 * @param {object} Obj
 * @param {string} Obj.url
 * @param {any} Obj.data
 * @param {string} Obj.method
 * @return {*}
 */

export default function ({
  url,
  data,
  method,
  contentType = 'application/json',
  showLoading = false
}) {
  let urlstring = `${BASE_URL}${url}`
  let token = ''
  try {
    token = wx.getStorageSync('token')
  } catch (err) {
    console.log('e: ', err)
  }
  token = token && JSON.parse(token)
  if (contentType === 'application/x-www-form-urlencoded') {
    data = qs.stringify(data)
  }
  
  return new Promise((resolve, reject) => {
    showLoading && wx.showLoading({ title: '加载中', mask: true })
    wx.request({
      url: urlstring,
      header: {
        'content-type': contentType,
        deviceTag: 'app', // 不加deviceTag token无效
        token: token
      },
      data,
      method,
      success(res) {
        wx.hideLoading()
        resolve(res)
      },
      fail(err) {
        reject(err)
      }
    })
  })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

# 挂载内容到this上

Object.defineProperty(Object.prototype, '__root', {
      get() {
        let obj = { name: 'zs' }
        obj.print = function (msg) {
          console.log(msg)
        }
        return obj
      },
      configurable: false,
      enumerable: false
    })
1
2
3
4
5
6
7
8
9
10
11

# 小程序封装Echarts

大体思路是监听图表的数据变化,通过setOption重新渲染图表。

import * as echarts from '../../../miniprogram_npm/ec-canvas/echarts'
const computedBehavior = require('miniprogram-computed').behavior
/* 图表模板 */
var option = {
  backgroundColor: 'rgba(236,243,251,1)',
  color: ['#eb5b5b', '#f9c14e', '#4a65bf', '#86c56a'],
  graphic: {
    type: 'text',
    left: 'center',
    top: '44%',
    style: {
      text: '',
      textAlign: 'center',
      fill: '#3783e8',
      fontSize: 14,
      fontWeight: 400
    }
  },
  series: [
    {
      label: {
        // normal: {
        fontSize: 14
        // }
      },
      type: 'pie',
      center: ['50%', '50%'],
      radius: ['60%', '80%'],
      data: []
    }
  ]
}
var chart = null
function initChart(canvas, width, height, dpr) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  })
  canvas.setChart(chart)
  chart.setOption(option)
  return chart
}

Component({
  behaviors: [computedBehavior],
  properties: {
    data: Array,
    graphicText: String
  },
  data: {
    ec: {
      onInit: initChart
    }
  },
  watch: {
    data(newVal) {
      // console.log('newVal: ', newVal);
      option.series[0].data = newVal
      option.graphic.style.text = this.properties.graphicText
      // 重新渲染图表
      chart?.setOption(option)
    }
  },
})

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

# 小程序按需注入

https://developers.weixin.qq.com/miniprogram/dev/framework/ability/lazyload.html

In app.json

{
  "lazyCodeLoading": "requiredComponents"
}
1
2
3

# api封装

const config = require('../config/index')
import qs from 'querystring'
const BASE_URL = config.BASE_URL
/**
 * @description: 发起请求
 * @param {object} Obj
 * @param {string} Obj.url
 * @param {any} Obj.data
 * @param {string} Obj.method
 * @param {string} Obj.contentType
 * @param {boolean} Obj.showLoading default=>false
 * @return {*}
 */
export default function ({
  url,
  data,
  method,
  contentType = 'application/json',
  showLoading = false
}) {
  let urlstring = ''
  // 表单查询
  if (contentType === 'application/x-www-form-urlencoded') {
    urlstring = `${BASE_URL}${url}?${qs.stringify(data)}`
  } else urlstring = `${BASE_URL}${url}`
  // console.log('urlstring: ', urlstring);
  let token = ''
  try {
    token = wx.getStorageSync('token')
  } catch (err) {
    console.log('获取token失败: ', err)
  }
  token = token && JSON.parse(token)
  // const token = `eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMSIsImlhdCI6MTYzNzY1Nzk0MCwiZXhwIjoxNjM4MjYyNzQwfQ.nvTyLA9F_yKm7_9lV-eOB25YpTT5EU3_F6PR3qWAC16cvDZFUFCKkIrb2sP_QwazPvAnaKP0RaWu1DY4Q1-xnw`
  // console.log('token: ', token)

  return new Promise((resolve, reject) => {
    showLoading && wx.showLoading({ title: '加载中', mask: true })
    wx.request({
      url: urlstring,
      header: {
        'content-type': contentType,
        deviceTag: 'app', // 不加deviceTag token无效
        token: token
      },
      data: contentType === 'application/json' ? data : '',
      method,
      success(res) {
        wx.hideLoading()
        if (res.data.code === 200) {
          resolve(res)
        } else if (res.data.code === 404 || res.data.code === 500) {
          wx.showModal({
            title: '提示',
            content: res.data.msg || '网络错误,请稍后重试',
            showCancel: false
          })
        } else if (res.data.code === 100001) {
          wx.showModal({
            title: '提示',
            content: '登录失效,请重新登录',
            showCancel: false,
            success() {
              wx.redirectTo({ url: '/pages/login/index' })
            }
          })
        } else if (res.data.code === 100002 || res.data.code === 100004) {
          wx.showModal({
            title: '提示',
            content: '请先登录',
            showCancel: false,
            success() {
              wx.redirectTo({ url: '/pages/login/index' })
            }
          })
        }
      },
      fail(err) {
        reject(err)
      }
    })
  })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83

# 获取定位

小程序获取定位重点有两条:

  • 通过微信小程序api: wx.getLocation获取当前所在的经纬度
  • 通过经纬度在腾讯开放平台地图上显示位置

# wx.getLocation

wx.getLocation({
      type: 'gcj02'
    }).then(res => {
      console.log('success', res)
      const { latitude, longitude } = res

      wx.openLocation({
        latitude,
        longitude,
      })
    }).catch(err => {
      console.log('error', err)
    })
1
2
3
4
5
6
7
8
9
10
11
12
13