Vue3-ts uni-APP engineering template construction

This is the 23rd day of my participation in Gwen Challenge

preface

A preliminary usable engineering template for UNI-Vue3-TS was built in the last phase

Features such as Vue3,TS,Sass, and Vant syndrome are included

This section adds more features to the template:

  • eslint
  • vuex4
  • mini-axios

eslint

By incorporating ESLint, you can constrain the coding styles of developers, making it easier to unify the development styles of members of a team

With the ESLint plugin in VS Code, you can automatically format according to configured rules

yarn add eslint --dev
Copy the code

Then add the script to package.json

{
  "scripts": {
    "eslint:init": "eslint --init"}}Copy the code

Execute the script

yarn eslint:init
Copy the code

Follow the prompts and choose some features according to your personal preference

After a few moments of quiet waiting, all dependencies are installed, and the eslintrc.js configuration file is automatically generated in the root directory

Plugin :vue/essential plugin:vue/vue3-essential

module.exports = {
  env: {
    browser: true.es2021: true,},extends: ['plugin:vue/vue3-essential'.'airbnb-base'].parserOptions: {
    ecmaVersion: 12.parser: '@typescript-eslint/parser'.sourceType: 'module',},plugins: ['vue'.'@typescript-eslint'].rules: {}};Copy the code

Add.eslintignore files, ignoring some files or directories that do not check the format

dist
Copy the code

Add automatic Lint directives to package.json

{
  "scripts": {
    "lint": "eslint --fix --ext .js,.jsx,.ts,.vue ./src",}}Copy the code

Executing automatic Lint

yarn lint
Copy the code

vuex

An essential state management tool

The template relies on version 3.2.0 by default, namely Vex3. Here we use Vex4 (built specifically for Vue3).

yarn add vuex@next --save
Copy the code

Let’s write an actual demo to test it

The directory structure

First create the Store directory under SRC

Stores of the same service or page are stored in the same namespace in a modular manner

The directory structure is as follows:

SRC /store ├─ index.txt TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXT TXTCopy the code

Each module is stored in modules

These modules are introduced through index.ts and then exported uniformly

Sample module writing

Contains the state, getters, mutations, the actions of four parts

Implementations written in TS provide very friendly writing tips

src/store/modules/test.ts

import { Module } from 'vuex';

interface State {
  count: number;
}

const store: Module<State, unknown> = {
  namespaced: true.state() {
    return {
      count: 0}; },getters: {
    isEven(state) {
      return state.count % 2= = =0; }},// Can only synchronize
  mutations: {
    increase(state, num = 1) {
      state.count += num;
    },
    decrease(state) {
      state.count -= 1; }},// Support asynchrony, you can consider introducing apis
  actions: {
    increase(context, payload) {
      setTimeout(() = > {
        context.commit('increase', payload);
      }, 1000); ,}}};export default store;
Copy the code

Use of sample modules

Import the store modules defined above in the store/index.ts file and createStore instances through createStore

src/store/index.ts

import { createStore } from 'vuex';
import test from './modules/test';

// Create a new store instance.
const store = createStore({
  modules: {
    m1: test,
  },
});

export default store;
Copy the code

Use the store directly in main.ts

import { createApp } from 'vue';
import App from './App.vue';
/ / into the store
import store from './store/index';

const app = createApp(App);

// Register on Vue
app.use(store);

app.mount('#app');
Copy the code

Sample component writing

Write a component call using the Modules /test store module written above

M1 in this code is the alias set above when store/index.ts was introduced

Components as follows the SRC/components/VuexDemo. Vue

<template>
  <view class="vuex-demo">
    <text>{{count}} -- {{isEven? 'yes' : 'no' }}</text>
    <view>
      <view><button @click="synIncrease">To increase</button></view>
      <view><button @click="asyncIncrease">Asynchronous increase</button></view>
    </view>
  </view>
</template>

<script lang="ts">
import { computed, defineComponent } from 'vue';
import { useStore } from 'vuex';

export default defineComponent({
  setup() {
    const $store = useStore();
    / / for the state
    const count = computed(() = > $store.state.m1.count);
    / / for getters
    const isEven = computed(() = > $store.getters['m1/isEven']);
    // Open mutations
    const synIncrease = () = > $store.commit('m1/increase');
    // Invoke asynchronous methods (actions)
    const asyncIncrease = () = > $store.dispatch('m1/increase');
    return{ count, isEven, synIncrease, asyncIncrease, }; }});</script>
<style>
.vuex-demo {
  text-align: center;
}
</style>
Copy the code

The effect

Axios

Axios cannot be used directly in UNI-App because it is only compatible with nodes and Web. Uni.request is the network request method closed by UNI-App

Investigate and find a request library axios-MiniProgram that is available for uni-app wrapped according to Axios API style

Here is a limited version, after testing the latest version has some minor problems, can not work properly

Yarn add [email protected]Copy the code

Here’s how to encapsulate the library

The directory structure

SRC API directory, http.ts,index.ts,modules

SRC/API ├ ─ ─ HTTP. Ts# Encapsulate the calling method├ ─ ─ index. TsThe interface call method of each business module is exposed uniformly externally└ ─ ─ modules └ ─ ─ the user. The tsThe interface of the user module calls the method
Copy the code

http.ts

Where the requested baseURL is injected through the environment variable configuration file (.env)

.env

VUE_APP_AXIOS_BASEURL=http://localhost:3000
Copy the code

Register a request/response interceptor for AXIOS and set the default request header

Add authentication identity token in request interceptor, further processing in response interceptor based on returned status (unified warning popup, permission verification)

import axios from 'axios-miniprogram';

const http = axios;

// Request the base path
http.defaults.baseURL = process.env.AXIOS_BASEURL;
http.defaults.headers = {
  'content-Type': 'application/json'}; http.interceptors.request.use((config) = > {
    // All requests carry tokens
    Object.assign(config.headers, {
      token: uni.getStorageSync('token')});// Operate config before sending
    return config;
  },
  (err) = > {
    if(err.status ! = =200) {
      // Processing error
    }
    return Promise.reject(err); });/** * Response interception */
http.interceptors.response.use(
  (response: any) = > {
    // Do some extra operations on the data (e.g., go directly to the home page without permission)
    const { code, msg } = response.data;
    if(code ! = =0) {
      if (msg) {
        uni.showToast({
          title: msg,
        });
      }
      // go catch logic
      return Promise.reject(response.data);
    }
    // Return before operation
    return response.data;
  },
  (err) = > Promise.reject(err),
);

export default http;
Copy the code

Interface modularization

The modules directory mainly writes the request methods of each service module

Such as modules/user. Ts

import http from '.. /http';

function login(account: string, pwd: string) {
  return http.post('user/login', {
    account,
    pwd,
  });
}

export default {
  login,
};
Copy the code

Unified exposure to the business side through API /index.ts

export { default as userApi } from './modules/user';
Copy the code

A business call

<script lang="ts">
import { defineComponent } from 'vue';
import { userApi } from '@/api';

export default defineComponent({
  setup() {
    const handleHttp = () = > {
      userApi.login('account'.'123456')
        .then((res) = > {
          console.log(res);
        }).catch((err) = > {
          console.log(err);
        });
    };
    return{ handleHttp, }; }});</script>
Copy the code

To be continued

  • tailwindcss
  • less
  • Remaining mature UI libraries
  • . and more

Data summary

  • Uni-vue3-ts: Template repository