


How to develop small programs using Taro + Vue3? (practice)
Jan 13, 2022 am 10:28 AMHow to use Taro3 Vue3 to develop small programs? The following article will introduce to you how to use Taro3 Vue3 to develop WeChat applet. I hope it will be helpful to you!
WeChat applet is an application that uses WeChat as the operating environment. Its essence is the application of Hybrid
technology. Hybrid App is a mixed-mode mobile application. , so it is similar to H5
, but has many native capabilities than H5, such as calling location information and cameras.
The development method of small programs is very similar to H5, and they also use JavaScript
, HTML
, CSS
languages.
Therefore, small program development can be said to be a skill that a front-end engineer must master.
There is a certain learning cost in developing native mini programs. Nowadays, there are many third-party multi-terminal frameworks for developing mini programs on the market. If you are not pursuing the ultimate performance and stability, it is better not to use native mini programs for development efficiency. too low.
Among the third-party multi-terminal frameworks, taro
and uni-app
are the most widely used. Generally speaking, when making technology selection, teams use react
, just use taro, the team uses vue
, and just use uni-app, there is no difference between the two, they are both very easy to use.
But many developers may not know that taro3.0 or above supports the use of vue. This article will introduce how to use Taro3 Vue3 to develop WeChat applets.
After I completed the construction of this project based on the information on the Internet, I developed a small program using this project. The development experience really surpassed all the projects I have developed in the past and was very smooth (maybe This is my first time writing a script setup for vue3, and it is really comfortable to use).
You can directly access this project github address clone and use.
Target function
- Integrate vue3, use
script setup
syntax development - Integration
Typescript
- Code inspection and format optimization
- Global state management
- Mini program subcontracting configuration
- Style encapsulation, compatible with notch screen and other style issues
- http method Encapsulation
Main technology stack
- Taro3
- Vue3
- TypeScript
- NutUi
- Pinia
When vue3 was first released, my enthusiasm for learning vue3 was directly discouraged due to the lack of suitable UI framework support. Until now, excellent frameworks such as quasar, element-plus, ant-design-vue have successively supported vue3, and many vue3 projects have been used in production environments. Only then did I realize that everyone was really using vue3.
For example, the project team next door to our company used vue3 for the reconstruction project. Only then did I realize that I was a little late in learning vue3 (tips: the front end is really too complicated)
NutUI is a JD-style mobile component library. It supports the use of Vue language to write applications that can be used on H5 and mini program platforms, helping developers improve development efficiency and development experience.
I learned about NutUI from Taro documentation. Taro officially recommends using NutUI for development. They all seem to be from the same development team on JD.com. I started using it with the mentality of giving it a try. , the user experience is not bad.
Pinia is a state management library for Vue, similar to Vuex, it is another state management solution for Vue, supporting Vue2 and Vue3.
The first time I came into contact with a front-end status management tool was a back-end management system of the company when I was an intern. It used dva. It was a torture and almost persuaded me to quit. I gradually became familiar with it, but whether I use redux or vuex, I still find it troublesome to write.
這次嘗試使用 Pinia,用起來(lái)確實(shí)很舒服,符合直覺(jué),易于學(xué)習(xí) ,有點(diǎn)類(lèi)似于 recoil,但沒(méi)有 recoil 那么多的概念和 API,主體非常精簡(jiǎn),極易上手。Pinia 快速入門(mén)
vscode 需安裝插件
- Eslint
- Prettier
- Volar
與vetur
相同,volar
是一個(gè)針對(duì) vue 的 vscode 插件,不過(guò)與 vetur 不同的是,volar 提供了更為強(qiáng)大的功能。
搭建項(xiàng)目架構(gòu)
初始化項(xiàng)目
初始化項(xiàng)目之前,需安裝 taro,請(qǐng)參考 Taro 文檔,完成 taro 安裝
使用命令創(chuàng)建模板項(xiàng)目:
taro init myApp
安裝 cli 用來(lái)執(zhí)行構(gòu)建等操作,之后啟動(dòng)項(xiàng)目,會(huì)生成一個(gè) dist 目錄
yarn add @tarojs/cli yarn dev:weapp
打開(kāi)微信開(kāi)發(fā)工具 工程目錄需要指向構(gòu)建出來(lái)的 dist 文件
Hello world 出現(xiàn),項(xiàng)目成功跑起來(lái)了!
設(shè)置代碼規(guī)范
- 代碼規(guī)范 ESlint
- 代碼格式化 Prettier
- 提交前檢查 husky
個(gè)人認(rèn)為,eslint + prettier 足以應(yīng)付大部分前端代碼規(guī)范問(wèn)題了,且配置起來(lái)很簡(jiǎn)單,有特殊需求也可繼續(xù)配置。
安裝依賴(lài)
yarn add @vue/eslint-config-prettier @vue/eslint-config-typescript eslint-plugin-prettier vue-tsc husky -D
設(shè)置代碼規(guī)范和格式化規(guī)則
.eslintrc.js
module.exports = { root: true, env: { node: true, 'vue/setup-compiler-macros': true }, extends: ['plugin:vue/vue3-essential', 'eslint:recommended', '@vue/prettier', '@vue/typescript'], parserOptions: { parser: '@typescript-eslint/parser' }, rules: { 'prettier/prettier': [ 'error', { singleQuote: true, semi: false, trailingComma: 'none', arrowParens: 'avoid', printWidth: 100 } ], 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off' } }
.prettierrc
{ "tabWidth": 2, "singleQuote": true, "semi": false, "trailingComma": "none", "arrowParens": "avoid", "endOfLine": "auto", "printWidth": 100 }
在 package.json 中 script 添加 Ts 檢查命令和 Eslint 檢查命令
"scripts":{ "tsc": "vue-tsc --noEmit --skipLibCheck", "lint": "eslint --ext .vue --ext .js --ext .ts src/" }
添加 husky 觸發(fā) Git 鉤子,代碼提交前檢查
npx husky install
編輯 pre-commit 執(zhí)行 Eslint 檢查和 Ts 檢查
#!/bin/sh . "$(dirname "$0")/_/husky.sh" echo "---eslint start---" npm run lint echo "---eslint end---" echo "---ts lint start---" npm run tsc echo "---ts lint end---"
至此,項(xiàng)目的代碼規(guī)范和格式規(guī)范配置完畢,多人協(xié)作也不是問(wèn)題了。
引入 NutUI
yarn add @nutui/nutui-taro
在 .babelrc
或 babel.config.js
中添加配置:
module.exports = { // ... plugins: [ [ 'import', { libraryName: '@nutui/nutui', libraryDirectory: 'dist/packages/_es', camel2DashComponentName: false }, 'nutui3-vue' ], [ 'import', { libraryName: '@nutui/nutui-taro', libraryDirectory: 'dist/packages/_es', camel2DashComponentName: false }, 'nutui3-taro' ] ] }
按需引入,安裝插件 babel-plugin-import
yarn add babel-plugin-import -D
樣式處理 因?yàn)?nutui 的設(shè)計(jì)稿是 375 的 所以將框架的設(shè)計(jì)尺寸調(diào)整為 375
項(xiàng)目配置文件 config/index.js 中配置:
designWidth: 375
app.ts
import { createApp } from 'vue' import { Button } from '@nutui/nutui-taro' const app = createApp() app.use(Button)
index.vue 中,nut-button 組件直接在 template 中寫(xiě),不用再引入
<template> <view class="index"> <text>{{ msg }}</text> <nut-button type="primary">主要按鈕</nut-button> </view> </template>
說(shuō)實(shí)話(huà),配置起來(lái)還是有點(diǎn)麻煩,不過(guò)按照官網(wǎng)文檔說(shuō)明來(lái)配也沒(méi)有踩坑,還行。
小程序分包配置
小程序主包超過(guò) 2M,就無(wú)法真機(jī)預(yù)覽了,為了提前做好準(zhǔn)備在一開(kāi)始就進(jìn)行分包處理。比如下面這個(gè)小程序的配置,分了四個(gè)包。
app.config.ts
pages: ['pages/create/index', 'pages/find/index', 'pages/my/index'], subpackages: [ { root: 'pages/featureA', pages: ['index/index'] }, { root: 'pagesSub/search', pages: ['index'] }, { root: 'pagesSub/my', pages: ['detail/index', 'about/index'] }, { root: 'pagesSub/book', pages: ['detail/index', 'person/list/index', 'person/detail/index'] } ],
可以在小程序開(kāi)發(fā)工具編輯器里的代碼依賴(lài)分析,查看主包和分包的大小
使用 script setup 語(yǔ)法封裝小程序頁(yè)面生命周期方法
hooks/life.ts
import { getCurrentInstance } from '@tarojs/taro' import { onMounted } from 'vue' const Current = getCurrentInstance() export function useDidShow(callback) { onMounted(callback) Current?.page?.onShow && (Current.page.onShow = callback) } export function usePullDownRefresh(callback) { Current?.page?.onPullDownRefresh && (Current.page.onPullDownRefresh = callback) }
使用
import { useDidShow } from '@/hooks/life' useDidShow(() => { // console.log('onShow') })
安裝 Pinia 進(jìn)行狀態(tài)管理
yarn add pinia yarn add taro-plugin-pinia
項(xiàng)目配置文件 config/index.js 中配置:
plugins: ['taro-plugin-pinia']
以管理用戶(hù)信息和用戶(hù)登錄狀態(tài)為例,實(shí)現(xiàn)一個(gè)用戶(hù)登錄功能
需要處理的文件代碼如下:
stores/auth.ts
import { defineStore } from 'pinia' interface UserInfoProp { nickName: string avatarUrl: string } const useAuth = defineStore({ id: 'authInfo', state: () => ({ userInfo: { nickName: '', avatarUrl: '' }, isLogin: false }), actions: { login() { this.isLogin = true }, logout() { this.isLogin = false }, setUserInfo(userInfo: UserInfoProp) { this.userInfo = userInfo } } }) export { useAuth }
stores/index.ts
import { createPinia } from 'pinia' import { useAuth } from './auth' export const store = createPinia() const storeObj = { auth: useAuth } // 封裝成useStore的形式,這樣一看引用就知道是store的數(shù)據(jù) export function useStore(key: string) { return storeObj[key]() }
個(gè)人中心 index.vue
<template> <main v-if="isLogin"> <user-info /> </main> <main v-else> <nut-button type="primary" @click="handleLogin">微信一鍵登錄</nut-button> </main> </template> <script setup> import Taro from '@tarojs/taro' import { computed } from 'vue' import { useStore } from '@/stores' import UserInfo from './userInfo.vue' const auth = useStore('auth') const isLogin = computed(() => auth.isLogin) const handleLogin = () => { setTimeout(() => { // 模擬后端請(qǐng)求得到token和userInfo Taro.setStorageSync('token', 'xxxx') auth.setUserInfo({ nickName: '林', avatarUrl: 'https://img12.360buyimg.com/imagetools/jfs/t1/143702/31/16654/116794/5fc6f541Edebf8a57/4138097748889987.png' }) auth.login() }, 500) } </script> </script>
userInfo 組件
<template> <article> <nut-avatar size="large" :icon="userInfo.avatarUrl"></nut-avatar> <span class="ellipsis name">{{ userInfo.nickName }}</span> </article> </template> <script setup> import Taro from '@tarojs/taro' import { computed } from 'vue' import { useStore } from '@/stores' const auth = useStore('auth') const userInfo = computed(() => auth.userInfo) </script>
總的來(lái)說(shuō), pinia 寫(xiě)起來(lái)是非常簡(jiǎn)潔的,這種類(lèi) react hooks 的寫(xiě)法,我是非常喜歡的
請(qǐng)求方法封裝
http.ts
// 封裝axios的請(qǐng)求,返回重新封裝的數(shù)據(jù)格式 // 對(duì)錯(cuò)誤的統(tǒng)一處理 import { HttpResponse } from '@/common/interface' import Taro from '@tarojs/taro' import publicConfig from '@/config/index' import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, Canceler } from 'axios-miniprogram' import errorHandle from '../common/errorHandle' const CancelToken = axios.CancelToken class HttpRequest { private baseUrl: string private pending: Record<string, Canceler> constructor(baseUrl: string) { this.baseUrl = baseUrl this.pending = {} } // 獲取axios配置 getInsideConfig() { const config = { baseURL: this.baseUrl, headers: { 'Content-Type': 'application/json;charset=utf-8' }, timeout: 10000 } return config } removePending(key: string, isRequest = false) { if (this.pending[key] && isRequest) { this.pending[key]('取消重復(fù)請(qǐng)求') } delete this.pending[key] } // 設(shè)定攔截器 interceptors(instance: AxiosInstance) { instance.interceptors.request.use( config => { console.log('config :>> ', config) let isPublic = false publicConfig.publicPath.map(path => { isPublic = isPublic || path.test(config.url || '') }) const token = Taro.getStorageSync('token') if (!isPublic && token) { config.headers.Authorization = 'Bearer ' + token } const key = config.url + '&' + config.method this.removePending(key, true) config.cancelToken = new CancelToken(c => { this.pending[key] = c }) return config }, err => { errorHandle(err) return Promise.reject(err) } ) // 響應(yīng)請(qǐng)求的攔截器 instance.interceptors.response.use( res => { const key = res.config.url + '&' + res.config.method this.removePending(key) if (res.status === 200) { return Promise.resolve(res.data) } else { return Promise.reject(res) } }, err => { errorHandle(err) return Promise.reject(err) } ) } // 創(chuàng)建實(shí)例 request(options: AxiosRequestConfig) { const instance = axios.create() const newOptions = Object.assign(this.getInsideConfig(), options) this.interceptors(instance) return instance(newOptions) } get(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse> | Promise<HttpResponse> { const options = Object.assign( { method: 'get', url: url }, config ) return this.request(options) } post(url: string, data?: unknown): Promise<AxiosResponse> | Promise<HttpResponse> { return this.request({ method: 'post', url: url, data: data }) } } export default HttpRequest
request.ts
import HttpRequest from './http' import config from '@/config/index' const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro const request = new HttpRequest(baseUrl) export default request
以獲取圖書(shū)列表和圖書(shū)詳情為例
apis/book.ts
import request from '../request' export function getBookList() { return request.get('books/getBookList') } export function getBookDetail(id: number) { return request.post('books/getBookDetail', { id }) }
請(qǐng)求方法封裝還是用到了 axios
,只是用的是 axios-miniprogram
,寫(xiě)法和 web 端基本一致,http.js 文件引用的一些模塊太多,本文沒(méi)有列出來(lái),可以直接訪(fǎng)問(wèn)本項(xiàng)目 github 地址查看。
樣式封裝
iPhoneX 底部橫線(xiàn)適配
assets/styles/common.scss
.safe-area-bottom { padding-bottom: constant(safe-area-inset-bottom); padding-bottom: env(safe-area-inset-bottom); }
劉海兒屏適配
assets/styles/hairline.scss
@mixin hairline-common() { position: absolute; box-sizing: border-box; content: ' '; pointer-events: none; } @mixin hairline() { @include hairline-common(); top: -50%; right: -50%; bottom: -50%; left: -50%; border: 0 solid #eaeaea; transform: scale(0.5); } @mixin hairline-top($color, $left: 0, $right: 0) { @include hairline-common(); top: 0; right: $right; left: $left; border-top: 1px solid $color; transform: scaleY(0.5); } @mixin hairline-bottom($color, $left: 0, $right: 0) { @include hairline-common(); right: $right; bottom: 0; left: $left; border-bottom: 1px solid $color; transform: scaleY(0.5); } [class*='van-hairline'] { &::after { @include hairline(); } } .van-hairline { &, &--top, &--left, &--right, &--bottom, &--surround, &--top-bottom { position: relative; } &--top::after { border-top-width: 1px; } &--left::after { border-left-width: 1px; } &--right::after { border-right-width: 1px; } &--bottom::after { border-bottom-width: 1px; } &, &-unset { &--top-bottom::after { border-width: 1px 0; } } &--surround::after { border-width: 1px; } }
多行文字省略
assets/styles/ellipsis.scss
@mixin multi-ellipsis($lines) { display: -webkit-box; overflow: hidden; text-overflow: ellipsis; -webkit-line-clamp: $lines; -webkit-box-orient: vertical; } @mixin ellipsis() { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .ellipsis { @include ellipsis(); } .multi-ellipsis--l2 { @include multi-ellipsis(2); } .multi-ellipsis--l3 { @include multi-ellipsis(3); }
總結(jié)
至此,終于完成了 Taro + Vue3 的項(xiàng)目搭建,強(qiáng)烈建議直接訪(fǎng)問(wèn)項(xiàng)目 github 地址 clone 使用,有一些配置細(xì)節(jié)本文無(wú)法一一列舉,就在項(xiàng)目中去發(fā)掘吧!
如果我的文章能幫助到你,那將是我的榮幸!
【相關(guān)學(xué)習(xí)推薦:小程序開(kāi)發(fā)教程】
The above is the detailed content of How to develop small programs using Taro + Vue3? (practice). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the <swiper> tag to achieve the switching effect of the carousel. In this component, you can pass b

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include
