加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

使用Taro框架开发小程序

发布时间:2020-12-14 19:34:03 所属栏目:资源 来源:网络整理
导读:最近一直在做小程序项目的开发,上手直接就是wepy,风格跟vue差不多,整体上,还算稳定,开发起来比原生的效率要高一点;很多人也知道,mpvue就是用vue搭建的,但始终觉得,失去了路由的vue,就像失去了灵魂;虽然接下来要给大家安利的框架,也貌似失去了该灵

最近一直在做小程序项目的开发,上手直接就是wepy,风格跟vue差不多,整体上,还算稳定,开发起来比原生的效率要高一点;很多人也知道,mpvue就是用vue搭建的,但始终觉得,失去了路由的vue,就像失去了灵魂;虽然接下来要给大家安利的框架,也貌似失去了该灵魂- taro框架(?Taro?是一套遵循React 语法规范的?多端开发?解决方案。)

taro开发文档:?nervjs.github.io/taro/docs/R…

有兴趣的可以去看看,在这里我将我初步入坑的学习过程,以及构建了大致矿建与大家分享下:

一:安装 Taro 开发工具?@tarojs/cli

npm install -g @tarojs/cli
复制代码

二:使用命令创建模板项目

可以根据自己的需要,选择是否使用ts,sass或者less,接着等安装好依赖,项目就构建完成;

三:项目目录结构

├── dist                   编译结果目录
├── config                 配置目录
|   ├── dev.js             开发时配置
|   ├── index.js           默认配置
|   └── prod.js            打包时配置
├── src                    源码目录
|   ├── pages              页面文件目录
|   |   ├── index          index页面目录
|   |   |   ├── index.js   index页面逻辑
|   |   |   └── index.css  index页面样式
|   ├── app.css            项目总通用样式
|   └── app.js             项目入口文件
└── package.json
复制代码

框架的使用和注意事项,文档中有介绍,我这边主要写一些项目配置和踩过的坑;

这里需要先安装一些依赖

代码规范 .prettierrc

{
    "stylelintIntegration": true,"tslintIntegration": "tabWidth": 2,0);">"singleQuote": "semi": false
}
复制代码

.prettierignore

/**/libs/**
dist/
lib/
复制代码

样式规范: .stylelintrc.js

module.exports = {
  ignoreFiles: ['**/*.md',0);">'**/*.ts',0);">'**/*.tsx',0);">'**/*.js']
}
复制代码

.stylelintignore

**/dist
复制代码

tslint.json

{
  "extends": ["tslint:recommended",0);">"tslint-config-prettier"],0);">"rules": {
    "ordered-imports": false,0);">"object-literal-sort-keys": "member-access": "member-ordering": "no-empty-interface": "no-console": ["warning"],0);">"interface-name": ["never-prefix"],0);">"no-empty": "quotemark": ["single"]
    // "semicolon": [false],// 结尾比较分号
    // "trailing-comma": ["requireForBlockBody": 

把所有问题都解决之后提交,当然tslint以及其他的一些配置都是自定义的,可以自己配置。觉得麻烦的可以根据自己的“口味”配置项目

然后我们就可以愉快的开发我们的项目,运行npm run dev:weapp,打开我们的小程序

很多人反馈用原生的 Taro.request或者用第三方axios等等做异步请求总会有错,我没亲测,但是自己用promise封装了方法,在根目录src文件夹下创建utils文件夹, 在这里我简单的模拟微信授权登录,以及检测session是否过期,绑定用户的场景写一个大概例子,接口为虚构:

├── utils                 
|   ├── api.ts            请求接口设置
|   ├── http.ts           http公共请求文件
|   └── index.ts          

复制代码

http.ts代码如下:

import md5 from 'blueimp-md5'

type HttpMethods = 'GET' | 'POST' | 'PUT' | 'DELETE'

// 后端是否支持json格式
const contentType = 'application/x-www-form-urlencoded'
// const contentType = 'application/json'

export default class Http {
  noNeedToken = ['mockFakeApi']

  get(url: string,data: object) {
    return this.commonHttp('GET',url,51); font-weight: 700;">data)
  }

  post(url: string,0);">'POST',51); font-weight: 700;">data)
  }

  async commonHttp(method: HttpMethods,url: string,51); font-weight: 700;">return new Promise<any>(async (resolve,reject) => {
      Taro.showNavigationBarLoading()
      try {
        const res = await Taro.request({
          url,method,51); font-weight: 700;">data,header: {
            'content-type': contentType
          }
        })
        Taro.hideNavigationBarLoading()
        switch (res.statusCode) {
          case 200:
            return resolve(res.data.response)
          default:
            console.log(res.data.message)
            reject(new Error(res.data.msg))
        }
      } catch (error) {
        Taro.hideNavigationBarLoading()
        reject(new Error('网络请求出错'))
      }
    })
  }
}

复制代码

api.ts


const http = new Http()

//  自动登录
const url = 'xxxxx'
export const login = (data: object) => http.post(url,data)

复制代码

index.ts (自定义公共处理接口文件)


// 获取微信登录凭证
const wxLogin = async () => {
  try {
    const res = await Taro.login()
    return res.code
  } catch (error) {
    console.log('微信获取临时凭着失败')
  }
}

const userLogin = await Taro.checkSession()
    if (!Taro.getStorageSync('token')) {
      throw new Error('本地没有缓存token')
    }
  } catch (error) {
    const code = await wxLogin()
    const loginRes: any = await login({
      code
      // ...(其他参数)
    })
    '用户数据',loginRes)
  }
}

复制代码

最后在pages/index/index.tsx中引用就好了


....

async componentDidMount() {
    await userLogin()
  }
复制代码

整个框架的使用大致就是这样了,react的书法风格还是挺舒服的,如果习惯了vue的写法可能刚开始会不习惯,有兴趣的可以尝试尝试,下面再简单的把一些小技巧给补上:

一:图片以模块的方式的引入

使用ts搭建的项目,引入静态资源,比如图片,会提示找不到模块,这时候就必须将图片声明为一个模块:

在types目录的global.d.ts文件下:

declare module ‘*.png’ {

? const img: any

? export default img

}

二:动态添加style

<View style={{backgroundImage: `url(${bgImg})`}}></View>
复制代码

三:动态添加class

1.<View className={data.length>0?’class-yes’: ’-no'}></View>

2.<View className={`common ${data.length>-no}`}></View>
复制代码

四:this的指向问题

1)在 Taro 的页面和组件类中,?this?指向的是 Taro 页面或组件的实例,如果我们要引用原生组件,需要使用到this的时候,如果如下引用:

Taro.createCanvasContext(canvasId,51); font-weight: 700;">this.$scope)
wx.createLivePlayerContext(liveId,51); font-weight: 700;">this.$scope)

错误:wx.createLivePlayerContext(liveId,this)这样引入是没有效果的,this并不是指向 wx.createLivePlayerContext.

(当前版本没有liveplayer的回调方法,所以直接用原生wx)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读