Detailed explanation of vite2.0+vue3 mobile project

Detailed explanation of vite2.0+vue3 mobile project

1. Technical points involved

  • vite version
  • vue3
  • ts
  • Integrated Routing
  • Integrate vuex
  • Integrate Axios
  • Configure Vant3
  • Mobile terminal adaptation
  • Request Agent

2. Steps

vite+ts+vue3 only needs one line of command

npm init @vitejs/app my-vue-app --template vue-ts

Configuring Routes

npm install vue-router@4 --save

Create a new router directory under src and create a new index.ts file

import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
const routes: Array<RouteRecordRaw> = [
 {
 path: "/",
 name: "Home",
 meta: {
  title: "Home",
  keepAlive: true
 },
 component: () => import("../views/Home/index.vue"),
 },
 {
 path: "/login",
 name: "Login",
 meta: {
  title: "Login",
  keepAlive: true
 },
 component: () => import("../views/Login/index.vue"),
 },
];
const router = createRouter({
 history: createWebHashHistory(),
 routes
});
export default router;

Mount the route in main.ts

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

Configure data center vuex (4.x)

Install

npm i vuex@next --save

Configuration

Create a store directory under src and create 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: {}
});

Mount

Mount the data center in main.ts

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')

Vant3

Install

npm i vant@next -S

The vite version does not need to configure the on-demand loading of components, because all modules in Vant 3.0 are written based on ESM and naturally have the ability to be introduced on demand, but all styles must be introduced 137.2k

Import styles globally in main.ts

import { createApp } from 'vue'
import App from './App.vue'
import router from "./router";
import store from "./store";
import 'vant/lib/index.css'; // Global import style createApp(App)
.use(router)
.use(store)
.use(ant)
.mount('#app')

Mobile terminal adaptation

Install postcss-pxtorem

npm install postcss-pxtorem -D

Create postcss.config.js in the root directory

module.exports = {
 "plugins": {
 "postcss-pxtorem": {
  rootValue: 37.5, 
  // Vant official root font size is 37.5
  propList: ['*'],
  selectorBlackList: ['.norem'] 
  // Filter out classes starting with .norem- and do not perform rem conversion}
 }
}

Create a new rem.ts file in the util directory in the root directory src.

// rem proportional adaptation configuration file // Base size const baseSize = 37.5 
// Note that this value should be consistent with the rootValue in the postcss.config.js file // Set rem function function setRem () {
 // The current page width is relative to the 375 width scaling ratio, which can be modified according to your needs. Generally, the design draft is 750 width (you can get the design drawing and modify it for convenience).
 const scale = document.documentElement.clientWidth / 375
 // Set the font size of the root node of the page ("Math.min(scale, 2)" means the maximum magnification ratio is 2, which can be adjusted according to actual business needs)
 document.documentElement.style.fontSize = baseSize * Math.min(scale, 2) + 'px'
}
// Initialize setRem()
// Reset rem when changing window size
window.onresize = function () {
 console.log("I executed")
 setRem()
}

Import in main.ts

import "./utils/rem"

Configure network request axios

Install

npm i -s axios

Configure Axios

Create a utils folder in src and create request.ts under utils

import axios from "axios";
const service = axios.create({
 baseURL,
 timeout: 5000 // request timeout
});
//Interceptor before initiating the request service.interceptors.request.use(
 config => {
 // If there is a token, carry token
 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.data;
 
 if (response.status !== 200) {
  return Promise.reject(new Error(res.message || "Error"));
 } else {
  return res;
 }
 },
 error => {
 return Promise.reject(error);
 }
);
export default service;

use

import request from "../utils/request";
request({url: "/profile ",method: "get"})
.then((res)=>{
 console.log(res)
})

Configuring the Request Agent

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 resolve: {
 alias:{
  '@': path.resolve(__dirname, './src') //Set alias}
 },
 server: {
 port:4000, //Start port open: true,
 proxy: {
  // Option writing '/api': 'http://123.56.85.24:5000'//Proxy URL},
 cors:true
 }
 
})

Above, a basic mobile terminal development configuration is completed.

3. Vite is particularly friendly to <script setup> and <style vars>

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>
<script setup>Writing <script lang="ts" setup="props">
import { useRouter } from "vue-router";
const router = useRouter();
const goLogin = () => {
 router.push("/");
};
</script>

Isn't it much simpler?

How to use <style vars>?
<script lang="ts" setup="props">
const state = reactive({
 color: "#ccc",
});
</script>
<style>
.text {
 color: v-bind("state.color");
}
</style>

It's that simple!

Code

Original address: zhuanlan.zhihu.com/p/351888882

Online preview: http://123.56.85.24/vite/#/

Code address: github.com/huoqingzhu/vue3-vite-ts-Vant

vitejs Chinese website: https://cn.vitejs.dev/

This is the end of this article about the practical details of vite2.0+vue3 mobile projects. For more relevant vite2.0+vue3 project practical content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vite+Electron to quickly build VUE3 desktop applications
  • How to add Vite support to old Vue projects
  • Implementation of Vue 3.x project based on Vite2.x
  • How to use vite to build vue3 application
  • What we have to say about Vue3 and Vite

<<:  Implementation of Linux command line wildcards and escape characters

>>:  Install and deploy java8 and mysql under centos7

Recommend

How to implement responsiveness in Vue source code learning

Table of contents Preface 1. Key Elements of a Re...

How to quickly create tens of millions of test data in MySQL

Remark: The amount of data in this article is 1 m...

React Fragment Introduction and Detailed Usage

Table of contents Preface Motivation for Fragment...

A brief discussion on the role of HTML empty links

Empty link: That is, there is no link with a targ...

Docker port mapping and external inaccessibility issues

The Docker container provides services and listen...

Example of adding music video to HTML page

1. Video tag Supports automatic playback in Firef...

MySQL 5.7.27 installation and configuration method graphic tutorial

The installation tutorial of MySQL 5.7.27 is reco...

WeChat Mini Program User Authorization Best Practices Guide

Preface When developing WeChat applets, you often...

Introduction to Nginx regular expression related parameters and rules

Preface Recently, I have been helping clients con...

MySQL learning notes: data engine

View the engines supported by the current databas...