微信小程序6

1.mobx-miniprogram

mobx-miniprogram是针对小程序开发的一个简单,高效,且轻量级的状态管理库,能提升小程序开发效率

2.创建store对象

详细使用步骤

javascript 复制代码
import { observable, action } from 'mobx-miniprogram'
 
export const numStore = observable({
 
  numA: 1,
  numB: 2,

  update: action(function () {
    this.numA+=1
    this.numB+=1
  }),
 
  get sum() {
    return this.numA + this.numB;
  }
 
})

在组件中使用store数据

方法1

在index.js中

javascript 复制代码
import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { numStore } from '../../stores/numstore'
 
ComponentWithStore({
  data: {
    someData: '...'
  },
  storeBindings: {
    store: numStore,
    fields: ['numA', 'numB', 'sum'],
    actions: ['update']
  }
}

方法2

在behavior.js中

javascript 复制代码
import { BehaviorWithStore } from 'mobx-miniprogram-bindings'
import { numStore } from '../../stores/numstore'
 
export const indexBehavior = BehaviorWithStore({
  storeBindings: {
    store: numStore,
    fields: ['numA', 'numB', 'sum'],
    actions: ['update'],
  }
})

在index.js中

javascript 复制代码
import { indexBehavior } from './behavior'
 
Page({
  behaviors: [indexBehavior]
 
})

3.fields,actions对象写法

fields,actions有两种写法,数组或对象

javascript 复制代码
import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { numStore } from '../../stores/numstore'
 
ComponentWithStore({
  data: {
    someData: '...'
  },
  storeBindings: {
    store: numStore,
    fields: {

      a: 'numA',
 
      b: () => store.numB,
 
      total: 'sub'
    },
 

    actions: {
      buttonTap: 'update'
    }
  }
})

4.绑定多个store以及命名空间

一个页面或组件可能会绑定多个store,这时可以将storeBinding改造成数组,数组每一项就是一个个遥绑定的store

javascript 复制代码
import { BehaviorWithStore } from 'mobx-miniprogram-bindings'
import { numStore } from '../../stores/numstore'
 
export const indexBehavior = BehaviorWithStore({
  storeBindings: [
    {
      namespace: 'numStore',
      store: numStore,
      fields: ['numA', 'numB', 'sum'],
      actions: ['update'],
    }
  ]
})

5.miniprogram-computed

小程序框架没有提供计算属性相关的Api,但是官方为开发者提供了拓展工具库miniprogram-computed

该库提供了两个功能

计算属性 computed

监听器 watch

在component.js中引入miniprogram-computed

计算属性

javascript 复制代码
import { ComponentWithComputed } from 'miniprogram-computed'
 
ComponentWithComputed({
  data: {
    a: 1,
    b: 1
  },
  
  computed: {
    total(data) {

      console.log('~~~~~')
        
      return data.a + data.b
    }
  }
})

监听器

javascript 复制代码
import { ComponentWithComputed } from 'miniprogram-computed'
 
ComponentWithComputed({
    
  data: {
    a: 1,
    b: 1
  },
    
  computed: {
    total(data) {
      return data.a + data.b
    }
  }
  
  watch: {
    'a, b': function (a, b) {
      this.setData({
        total: a + b
      })
    }
  },
  
  methods: {
    updateData() {
      this.setData({
        a: this.data.a + 1,
        b: this.data.b + 1
      })
    }
  }
})

6.用户登录

什么是token

登录流程介绍

登录功能

javascript 复制代码
import http from '../utils/http'
 

export const reqLogin = (code) => {
  return http.get(`/weixin/wxLogin/${code}`)
}
javascript 复制代码
import { reqLogin } from '../../api/user'
import { toast } from '../../utils/extendApi'
 
Page({
  login() {
    wx.login({
      success: async ({ code }) => {
        if (code) {
          const res = await reqLogin(code)
 
          wx.setStorageSync('token', res.data.token)
 
          wx.navigateBack()
        } else {
          toast({ title: '授权失败,请稍后再试~~~' })
        }
      }
    })
  }
})

7.token保存到store

javascript 复制代码
import { observable, action } from 'mobx-miniprogram'
import { getStorage } from '../utils/storage'
 
export const userStore = observable({
  token: getStorage('token') || '',
 
  setToken: action(function (token) {
    this.token = token
  })
})
javascript 复制代码
import { reqLogin } from '../../api/user'
 import { userStore } from '../../api/userstore'
 
 import { ComponentWithStore } from 'mobx-miniprogram-bindings'
 
 ComponentWithStore({
    
   storeBindings: {
     store: userStore,
     fields: ['token'],
     actions: ['setToken']
   }
 
   methods: {
    login() {
      wx.login({
        success: async ({ code }) => {
          if (code) {
            const { data } = await reqLogin(code)
 
            setStorage('token', data.token)
              
             this.setToken(data.token)
          } else {
            toast({ title: '授权失败,请重新授权' })
          }
        }
      })
    }
   }
})

8.用户信息存储到store

javascript 复制代码
export const reqUserInfo = () => {
  return http.get(`/mall-api/weixin/getuserInfo`)
}
javascript 复制代码
import { toast } from '../../utils/extendApi'

import { setStorage } from '../../utils/storage'

 import { reqLogin, reqUserInfo } from '../../api/user'
 

import { ComponentWithStore } from 'mobx-miniprogram-bindings'

import { userStore } from '../../stores/userstore'
 
ComponentWithStore({
  storeBindings: {
    store: userStore,
     fields: ['token', 'userInfo'],
     actions: ['setToken', 'setUserInfo']
  },
 
  methods: {
    login() {
      wx.login({
        success: async ({ code }) => {
          if (code) {
            const { data } = await reqLogin(code)
 
            setStorage('token', data.token)
 
            this.setToken(data.token)
              
           this.getUserInfo()
          } else {
            toast({ title: '授权失败,请重新授权' })
          }
        }
      })
    },
        
    async getUserInfo() {
      const { data } = await reqUserInfo()
      setStorage('userInfo', data)
     this.setUserInfo(data)
    }
  }
})

9.使用数据渲染用户信息

javascript 复制代码
 import { ComponentWithStore } from 'mobx-miniprogram-bindings'
 
 ComponentWithStore({
 
   storeBindings: {
     store: userStore,
     fields: ['token', 'userInfo']
   }
 
})
javascript 复制代码
<view class="container bg">
  <view class="top-show">
    <image mode="widthFix" class="top-show-img" src="/static/images/banner.jpg"></image>
  </view>
  <view class="wrap">
 
     <view class="user-container section" wx:if="{{ !token }}" bindtap="toLoginPage">
      <view class="avatar-container">
        <image src="/static/images/avatar.png"></image>
        <view class="no-login">
          <text class="ellipsis">未登录</text>
          <text>点击授权登录</text>
        </view>
      </view>
    </view>
 
     <view wx:else class="user-container section">
       <view class="avatar-container">
         <image src="{{ userInfo.headimgurl }}"></image>
         <view class="no-login">
           <text class="ellipsis">{{ userInfo.nickname }}</text>
         </view>
       </view>
       <view class="setting">
         设置
       </view>
     </view>
 
    <view class="order section">
      <view class="order-title-wrap">
        <text class="title">我的订单</text>
        <text class="more">查看更多></text>
      </view>
      <view class="order-content-wrap">
        <view class="order-content-item" wx:for="{{ initpanel }}">
           <navigator url="{{ token ? item.url : '/pages/login/login' }}">
            <view class="iconfont {{ item.iconfont }}"></view>
            <text>{{ item.title }}</text>
          </navigator>
        </view>
      </view>
    </view>
 
    <view class="after-scale section">
    </view>
 
    
  </view>
</view>
相关推荐
小蒜学长17 小时前
基于微信小程序的遇见咖啡店点餐系统设计与实现(代码+数据库+LW)
java·spring boot·后端·微信小程序·咖啡店点餐系统
今日热点18 小时前
小程序主体变更公证线上办理教程|2026 最新材料规范与审核避坑
小程序
Ai-_Man18 小时前
从聊天框到正式文档:AI导出鸭瞄准AI大模型应用的“最后一公里”
开发语言·前端·javascript·人工智能·小程序
省钱兄--zs1 天前
北京24小时自助健身房系统软件开发实战:从架构设计到部署指南
java·数据仓库·spring boot·小程序·需求分析
Ai-_Man1 天前
您您这可以把Grok的多个会话比如说。左侧的多个会话一次性导出吗?不是单条会话里面的多次会对话。AI导出鸭
javascript·人工智能·ai·小程序·电脑
光影少年1 天前
Taro 是如何解析入口配置 app.config.ts 和页面配置的?
微信小程序·小程序·typescript·reactjs·百度小程序·taro
用户788477316341 天前
门店核销闭环:小程序扫码 + .NET 幂等接口 + WPF 看板,一天能跑通
微信小程序·c#
DS小龙哥2 天前
从呼吸心率到离床报警:60G雷达睡眠仪全栈开发实录(硬件+MQTT+小程序)DIY一台全功能睡眠监护仪
stm32·单片机·嵌入式硬件·物联网·小程序·智能家居
扶风ff2 天前
练题簿在线免费刷题:刷题、背题、错题复习,一个小程序安排日常备考
学习·小程序
扶风ff2 天前
练题簿在线免费刷题:共享题库、学习任务、在线考试,岗位培训更方便
学习·小程序