当前位置: 首页 > 工具软件 > Taro UI > 使用案例 >

taro + taro ui + dva 微信小程序实践

冯德宇
2023-12-01

1. taro 安装:

参考taro官网;

  • 安装cli工具:
#使用 npm 安装 CLI
npm install -g @tarojs/cli

 注意,安装过程出现sass相关的安装错误,请在安装mirror-config-china后重试: 

 npm install -g mirror-config-china
  • 项目初始化
taro init myApp

   注意,初始化项目中如果有依赖安装失败的话需要手动安装:

npm install

2.运行

  •    微信开发工具下载,安装;

https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html

  • 开发环境运行命令:
npm run dev:weapp
  • 打包命令:
npm run build:weapp

到这里基础环境就安装完成,将启动的项目导入到微信开发工具中,就可以看到效果了。但是此时开发就只能用到taro将微信原生的组件转化成的react组件。

那有没有关于taro的ui库呢,请往下看:

3. 安装 taro-ui;

参考:taro-ui官网;

npm install taro-ui

安装完成后,我们就可以快乐的用taro-ui中的组件了;

4. 安装dva:

当前基础的组件库 和 ui 库已经有了,那么数据状态管理在react中经常难免会用到,此时我们用dva来管理状态,功能同 redux

npm install --save @tarojs/async-await
cnpm install --save redux @tarojs/redux @tarojs/redux-h5 redux-thunk redux-logger
npm i dva-core dva-loading --save

dva的使用方法:

  • utils下面创建dva配置文件dva.js
import { create } from 'dva-core';
import { createLogger } from 'redux-logger';
import createLoading from 'dva-loading';

let app;
let store;
let dispatch;

function createApp(opt) {
  // redux日志
  // opt.onAction = [createLogger()];
  app = create(opt);
  app.use(createLoading({}));

  if (!global.registered) opt.models.forEach(model => app.model(model));
  global.registered = true;
  app.start();

  store = app._store;
  app.getStore = () => store;

  dispatch = store.dispatch;

  app.dispatch = dispatch;
  return app;
}

export default {
  createApp,
  getDispatch() {
    return app.dispatch;
  }
}
  • 新建一个文件夹models 里面放所有的model文件,项目中有多个模块,在models文件夹中建一个index.js统一引入:
import homePage from './homePage';
import focusModel from './focusModel';
import addCarControl from './addCarControl';
import finSomeone from './findSomeone';
import mine from './mine';
import epidemicEntry from './epidemicEntry';
import memberManage from './memberManage';
import login from './login';
import watchMonitor from './watchMonitor';
import resident from './residentModel'
import teamManage from './teamManage'
import noticeModel from './noticeModel'

export default [homePage, focusModel, addCarControl, finSomeone, mine, epidemicEntry, memberManage, login, watchMonitor,
  resident, teamManage, noticeModel];
  • app.js引入dva.js 和model.js
import '@tarojs/async-await';
import Taro, { Component } from '@tarojs/taro'
import {connect, Provider} from '@tarojs/redux';
// import HomePage from './pages/HomePage/index'
import Login from './pages/Login/index'
import dva from './utils/dva';
import models from './models';
// import NoticePage from './pages/NoticePage/index'
// import Mine from './pages/Mine/index'
import './app.scss'

const dvaApp = dva.createApp({
  initialState: {},
  models: models,
});
const store = dvaApp.getStore();


// 如果需要在 h5 环境中开启 React Devtools
// 取消以下注释:
// if (process.env.NODE_ENV !== 'production' && process.env.TARO_ENV === 'h5')  {
//   require('nerv-devtools')
// }
class App extends Component {

  componentDidMount () {}

  componentDidShow () {}

  componentDidHide () {
    //每次退出小程序都清除token
    // Taro.removeStorageSync('token')
  }

  componentDidCatchError () {}

  config = {
    pages: [
      'pages/Login/index',
      'pages/Login/UnderReview/index',
      'pages/HomePage/index',
      'pages/Login/GroupInfo/index',
      'pages/HomePage/FindSomeone/index',
      'pages/HomePage/Focus/Partition',
      'pages/HomePage/Focus/PeopleDetail',
      'pages/HomePage/Focus/VehicleDetails',
      'pages/HomePage/ReturnRegistration/index',
      'pages/HomePage/ReturnRegistration/AddReturnData/index',
      'pages/HomePage/DynamicPeopleList/index',
      'pages/HomePage/UnnormalBehaviourDiscovery/unnormalDetail',
      'pages/HomePage/AttentionPerson/AttentionPersonDetail',
      'pages/HomePage/ResidentPopulation/index',
      'pages/HomePage/ResidentPopulation/PersonDetail/index',
      'pages/HomePage/ResidentInOutManage/index',
      'pages/HomePage/EntryOutAudit/index',
      'pages/NoticePage/index',
      'pages/NoticePage/AlarmList',
      'pages/NoticePage/ToDoList',
      'pages/Mine/index',
      'pages/Mine/UpdateRecord/index',
      'pages/Mine/AddDevice/index',
      'pages/Mine/LocalSettings/index',
      'pages/Mine/MemberManage/index',
      'pages/Mine/NewMemberPage/index',
      'pages/Mine/TeamManage/index',
      'pages/Mine/TeamManage/TeamDetail/index',
      'pages/Mine/TeamManage/TransferManage/index',
      'pages/Mine/TeamManage/CheckingDetail/index',
      'pages/Components/RangeSearch/index',
      'pages/Components/EpidemicEntry/index',
      'pages/Components/SearchDetail/index',
      'pages/Components/WatchMonitor/index',
      'pages/Components/VisitorManage/index',
      'pages/Components/AddVisitor/index',
      'pages/HomePage/Focus/EpidemicCarList',
      'pages/HomePage/Focus/EpidemicCarDetail',
      'pages/HomePage/Focus/AddCarControl',
      'pages/Components/VisitorDetail/index',
      'pages/Login/SelectTeam/index',
      'pages/Login/ApplyRecordList/index'
    ],
    window: {
      backgroundTextStyle: 'light',
      navigationBarBackgroundColor: '#fff',
      navigationBarTitleText: 'WeChat',
      navigationBarTextStyle: 'black'
    },
    tabBar: {
      color: '#999990',
      selectedColor: '#0089FF',
      list: [
        {
          pagePath: "pages/HomePage/index",
          text: "首页",
          iconPath: 'images/homeBar@3x.png',
          selectedIconPath: 'images/homeBar_active@3x.png'
        },
        {
          pagePath: "pages/NoticePage/index",
          text: "通知",
          iconPath: 'images/noticeBar@3x.png',
          selectedIconPath: 'images/noticeBar_active@3x.png'
        },
        {
          pagePath: "pages/Mine/index",
          text: "我",
          iconPath: 'images/mineBar@3x.png',
          selectedIconPath: 'images/mineBar_active@3x.png'
        }
      ]
    },
  }

  // 在 App 类中的 render() 函数没有实际作用
  // 请勿修改此函数
  render() {
    return (
      <Provider store={store}>
        <Login />
        {/* <HomePage /> */}
      </Provider>
    );
  }
}

Taro.render(<App />, document.getElementById('app'))

看一个子model.js的写法watchMonitor.js:

/*
 * @Author: g05047
 * @Date: 2020-02-22 13:21:46
 * @LastEditTime: 2020-02-27 13:31:36
 * @LastEditors: Please set LastEditors
 * @Description: 看监控
 * @FilePath: \yunyibao\src\models\watchMonitor.js
 */
import * as watchMonitorService from '../services/watchMonitorService'

const regeneratorRuntime = require('../utils/runtime.js')
export default {
    namespace: 'watchMonitor',
    state: {
        //设备列表
        cameraList: [],
        pageNum:1, //相机列表页号
        pageSize:100,//相机列表页行
        //回放url
        backPlayUrl: '',
        //实况url
        livePlayUrl:'',
        // 视频浓缩
        summaryPlayUrl:'',
        // 开始时间
        startTime:new Date().getTime()-5*60*1000, //回放的开始时间
        // 结束时间
        endTime:new Date().getTime(),// 回放的结束时间
        // 当前选中的相机
        selCameraValue:{}
    },
    effects: {
          // 获取设备列表
          *getCamreaList({ payload }, { call, put }) {
            const result = yield call(watchMonitorService.getCamreaList, payload);
            if (result.status === 200 && result.data) {
              const { rows = [] } = result.data;
              rows.forEach((item)=>{
                item.label = item.deviceName; //设备名称
                item.value = String(item.id);//设备唯一编码
              });
              yield put({
                    type: 'updateState',
                    payload: {
                        cameraList: rows,
                    }
                })
            }
          },
          // 获取实况url
          *getLiveVideoUrl({ payload }, { call, put }) {
            const result = yield call(watchMonitorService.getLiveVideoUrl, payload.requestParm);
            if (result.status === 200 && result.data) {
              yield put({
                    type: 'updateState',
                    payload: {
                      livePlayUrl:result.data.liveAddress || '',
                      selCameraValue:Object.assign({},payload.upDateParm.selCameraValue)
                    }
                })
            }
        },
        // 获取回放url
        *getVideoUrl({ payload }, { call, put }) {
          const result = yield call(watchMonitorService.getVideoUrl, payload.requestParm);
          if (result.status === 200) {
            yield put({
                  type: 'updateState',
                  payload: {
                    backPlayUrl:result.data || '',
                    selCameraValue:Object.assign({},payload.upDateParm.selCameraValue),
                    startTime:payload.upDateParm.startTime,
                    endTime:payload.upDateParm.endTime
                  }
              })
          }
        },
        // 获取视频浓缩url
        *getSummaryVodeoUrl({ payload }, { call, put }) {
            const result = yield call(watchMonitorService.getSummaryVodeoUrl, payload.requestParm);
            if (result.status === 200) {
              yield put({
                    type: 'updateState',
                    payload: {
                      summaryPlayUrl:result.data || '',
                      selCameraValue:Object.assign({},payload.upDateParm.selCameraValue),
                      startTime:payload.upDateParm.startTime,
                      endTime:payload.upDateParm.endTime
                    }
                })
            }
        }
    },
    reducers: {
      updateState(state, { payload }) {
        return { ...state, ...payload };
      }
    }
}

项目仓库地址:https://gitee.com/JaggerGuo/taro-taroui-dva-miniprogram.git

 

 类似资料: