Vite 2.0 builds Vue3 mobile terminal project

First, it involves technical points

  • vite
  • vue3
  • ts
  • router
  • vuex
  • axios
  • vant3
  • Mobile adaptation
  • Request broker

Step 2.

Vite +ts+vue3 requires only one command

npm init @vitejs/app my-vue-app --template vue-ts
Copy the code

Initialize the project

npm install
npm run dev
Copy the code

Install the typescript

  1. Create a file in the root directory of your project: tsconfig.json
/ / specifies the root file used to compile the project and compile options / / configuration reference https://www.tslang.cn/docs/handbook/tsconfig-json.html {" compilerOptions ": {" target" : "Esnext ", "module": "esnext", "strict": true, // This makes strict inference about data attributes on 'this', otherwise it is always treated as any type" JSX ": "Preserve", and "moduleResolution" : "node"}, "include:" ["/SRC / * * * ", "SRC/main which s" / / * * / recursive match any subdirectory], "exclude" : [ "node_modules" ] }Copy the code
  1. Change SRC /main.js to SRC /main.ts
  2. Change main.js imported in the index. HTML directory to main.ts
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="icon" href="/favicon.ico" /> <meta name="viewport" content="width=device-width, Initial - scale = 1.0 "> < title > Vite App < / title > < / head > < body > < div id =" App "> < / div > <! --<script type="module" src="/src/main.js"></script>--> <script type="module" src="/src/main.ts"></script> </body>Copy the code
  1. Change the entry file of the project to main.ts and create the file vue.config.js in the root directory of the project
module.exports = {
    pages: {
        index: {
            entry: 'src/main.ts'
        }
    }
};
Copy the code

After the above steps, you will find that the project still starts normally, but you will find an error in main.ts

/ SRC/ts /.vue/ts /.vue/ts /.vue /.vue/ts /.vue /.vue /.vue /.vue /.vue /.vue /.vue

// When you don't use something that needs to be defined, // SRC /main.d.ts declare Module '*. Vue '{/* import {ComponentOptions} from 'vue'; // SRC /main.d.ts declare Module '*. const componentOptions: ComponentOptions; export default componentOptions; * /}Copy the code

Note: Give the.d.ts file a filename, such as a.d.ts, otherwise esLint won’t be able to format it; Also do not name the entry file with the.d.ts file, otherwise the.d.ts file will not take effect

** Configure routes **

  1. Make sure to install vue-Router with the version number; otherwise, the current version is still 3.x
npm install vue-router@4
Copy the code
  1. Create a router folder (SRC/router) and create an index.ts file under router:
Import {createRouter, createWebHashHistory} from 'vue-router'; import {createRouter, createWebHashHistory} from 'vue-router'; const routes = [ { path: '/', redirect: '/home', }, { path: '/home', component: () => import('../components/home.vue') } ]; Const router = createRouter({history: createWebHashHistory(), // replace mode, required routes}); export default router;Copy the code
  1. Modify the SRC/main. Ts:
import {createApp} from 'vue'; import App from './App.vue'; import router from './router/index'; // import vue-router import './index.css'; const app = createApp(App); app.use(router); App.mount ('#app');Copy the code

Configuring vuEX for State Management (4.x)

  1. The installation
npm i vuex@next --save
Copy the code
  1. configuration

Create the store directory under SRC and index.ts under store

import { createStore } from "vuex";
export default createStore({
  state: {
    listData:{1:10},
    num:10
  },
  mutations: {
    setData(state,value){
        state.listData=value
    },
    addNum(state){
      state.num=state.num+10
    }
  },
  actions: {
    setData(context,value){
      context.commit('setData',value)
    },
  },
  modules: {}
});
Copy the code
  1. mount

In the main. Ts mount

import { createApp } from 'vue'
import App from './App.vue'
import router from "./router";
import store from "./store";
createApp(App)
.use(router)
.use(store)
.mount('#app')
Copy the code

Vant3

  1. The installation
npm i vant@next -S
Copy the code

The Vite version does not require the on-demand loading of configuration components because all modules in Vant 3.0 are written based on ESM and naturally have the ability to be imported on demand, but styles must be fully imported at 137.2k

  1. Introduce styles globally in main.ts
import { createApp } from 'vue' import App from './App.vue' import router from "./router"; import store from "./store"; import vant from 'vant' import 'vant/lib/index.css'; CreateApp (App).use(router).use(store).use(vant).mount('# App ')Copy the code

Configure the network request AXIos

  1. The installation
npm i -s axios
Copy the code
  1. Configuration axios

Create the utils folder in SRC and request.ts under utils

import axios from "axios"; const service = axios.create({ baseURL, timeout: 5000 // request timeout }); / / before initiating the interceptor service. The interceptors. Request. Use (config = > {/ / if a token to carry tokon const token = window.localStorage.getItem("accessToken"); if (token) { config.headers.common.Authorization = token; } return config; }, error => Promise.reject(error) ); / / response interceptor service. Interceptors. Response. Use (response = > {const res = response. The data; if (response.status ! == 200) { return Promise.reject(new Error(res.message || "Error")); } else { return res; } }, error => { return Promise.reject(error); }); export default service;Copy the code
  1. use
import request from ".. /utils/request"; request({url: "/profile ",method: "get"}) .then((res)=>{ console.log(res) })Copy the code

Configuring the request broker

vite.config.ts

import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import path from 'path'; / / https://vitejs.dev/config/ export default defineConfig ({plugins: [vue ()], base: ". / ", / / packaging path to resolve: {alias: {' @ ': Path. resolve(__dirname, './ SRC ')// Set alias}}, server: {port:4000,// start port open: true, proxy: {// option '/ API ': 'http://123.56.85.24:5000' / / proxy}, cors: true}})Copy the code

Mobile adaptation (PostCSS-Pxtorem)

  1. Install postcss – pxtorem
npm install postcss-pxtorem -D
Copy the code
  1. Create postcss.config.js in the root directory
Module. exports = {"plugins": {"postcss-pxtorem": {rootValue: 37.5, // Vant official root size is 37.5 propList: ['*'], selectorBlackList: ['.norem'] // norem- class, norem conversion}}}Copy the code
  1. Create the rem.ts equal ratio adaptation file under the new util directory in the root directory SRC
// rem equal ratio configuration file // baseSize const baseSize = 37.5 // note that this value must be consistent with rootValue in postcss.config.js // setRem function function setRem () {// The current page width relative to the 375 width scale, can be modified according to your needs, generally the design is 750 wide. Const scale = document. DocumentElement. ClientWidth / 375 / / set the page root node font size (" Math. Min (scale, 2) "refers to the maximum magnification ratio of 2, ) can be adjusted according to actual business requirements document. The documentElement. Style.css. FontSize = baseSize * Math. Min (scale, Onresize = function () {console.log(" I did it ") setRem()}Copy the code
  1. The mian. Ts introduced
import "./utils/rem"
Copy the code

Above, a basic mobile development configuration is complete.

3. Vite right<script setup><style vars>Support has been extraordinarily friendly

Normal writing

<script lang="ts"> import { defineComponent } from "vue"; import { useRouter } from "vue-router"; export default defineComponent({ setup() { const router = useRouter(); const goLogin = () => { router.push("/"); }; return { goLogin }; }}); </script>Copy the code

<script setup>writing

<script lang="ts" setup="props">
import { useRouter } from "vue-router";
const router = useRouter();
const goLogin = () => {
  router.push("/");
};
</script>
Copy the code

Isn’t that much simpler

<style vars>How to use?

<script lang="ts" setup="props">
const state = reactive({
  color: "#ccc",
});
</script>
Copy the code
<style >
.text {
  color: v-bind("state.color");
}/
</style>
Copy the code

It’s that simple!