移动端使用vue3+vite+vant总结

1,921 阅读5分钟

背景:

前几天PM拉着去开会,说是以后侧重移动端,让我们做技术支持。这个移动端页面主要有App端内嵌H5,企业微信端,小程序端内嵌H5,以及在在浏览器打开的页面等。

使用技术

这个项目主要运行在移动端,结合现在前端小组技术能力,打算采用vue3+vite+vant

调研:

主要是调研vue3在App端兼容性

1.对import 的兼容性

1.1 安卓4.4.4 以下的不支持,占用率 0.35%。
1.2 IOS:10.3 以下;占用率:0.39%;

2.Proxy 兼容性

 2.1 IOS:9.3 以上;
 2.2 安卓:4.4.4 以上;

安卓4.4.4 是2014年发布的 IOS:9.3 是2016年发布的,市场占有率:0.35% 很低了

参考链接:www.zhihu.com/question/44…

项目初始化

1.安装vite+vue3

npm create vite@latest

image.png

2.启动项目

  cd vite-project
  npm install    
  npm run dev 

image.png

路由模块vue-router

1.安装

npm install vue-router@4

通过在package.json查看安装的版本

image.png

2 配置路由

2.1 在main.js中注册

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

2.2 在src文件中建立App模块页面和企微微信模块页面

image.png

2.3 初始化路由

同样在src中新建router文件夹,下图这是路由总体架构

image.png

router/index.js为路由的总管理就是将App端和企微端路由汇总在一起

image.png

router/app/index.js为App端模块路由管理

image.png

router/app/agreement/index.js为App端模块各个迭代版本路由管理

image.png

然后在App.vue增加

image.png

2.4 解决路径别名问题

启动项目然后输入http://localhost:3000/#/app/agreement/index 就会发现如下报错

image.png 这是无法识别别名路径 所以需要安装path模块来处理

npm install path

path安装完毕需要在vite.config.js 设置下

image.png

然后启动项目就可以看见页面了

image.png

引入vant框架

安装vant

npm i vant

按需引入组件

npm i vite-plugin-style-import@1.4.1 -D

配置插件

安装完成后,在 vite.config.js 文件中配置插件

image.png

页面按需引入组件

image.png

启动效果

image.png

引入scss

npm install --save-dev sass

引入测试

image.png

测试效果

image.png

关于移动端适配问题

1.禁止在移动端页面拖动 放大和ios端自动将你的数字转化为拨号连接等

在index.html页面增加

<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
<meta name="format-detection" content="telephone=no, email=no, date=no, address=no">

2 Viewport 布局

使用postcss-px-to-viewport 是一款 PostCSS 插件,用于将 px 单位转化为 vw/vh 单位。

 npm install postcss-px-to-viewport --save-dev

在根目录下新建postcss.config.js

module.exports = {
    plugins: {
        'postcss-px-to-viewport': {
            viewportWidth: 750,
            exclude: [/node_modules/, /\/src\/assets\//, /index.html/],
            include: [/\/src\/view\//, /\/src\/components\//]
        }  
    }
}

效果如下

image.png

关于代码检查-Eslint

安装

npm install --save-dev eslint eslint-plugin-vue

创建.eslintrc.js

在根目录下创建.eslintrc.js来设置匹配规则

module.exports = {
    'env': {
        'browser': true,
        'es2021': true
    },
    'globals': {  // 使用未在当前文件中定义的全局变量时,会命中 no-undef 规则,通过 globals 配置指定的全局变量无视 no-undef 规则
        '__dirname': true,
        'module': true,
        'process': true
    },
    'extends': [
        'eslint:recommended',
        'plugin:vue/essential',
    ],
    'parserOptions': {
        'ecmaVersion': 'latest',
        'sourceType': 'module'
    },
    'plugins': [
        'vue'
    ],
    rules: {
        // 代码风格-因人而异
    }
}

eslint官网

创建.eslintignore

该文件为不希望用eslint去匹配的

dist/
node_modules/
.eslintrc.js

关于样式风格检查-styleLint

安装

npm install --save-dev stylelint stylelint-config-recommended-scss stylelint-config-recommended-vue stylelint-config-standard stylelint-scss  postcss-html

创建.stylelintrc文件

{
	"plugins": ["stylelint-scss"],
	"extends": [
		"stylelint-config-standard",
		"stylelint-config-recess-order",
		"stylelint-config-prettier"
	],
	"rules": {
		"indentation": 4,
                "rule-empty-line-before": "never",
                "at-rule-empty-line-before": "never",
                "declaration-colon-space-after":"always",
		"at-rule-no-unknown": [
			true,
			{
				"ignoreAtRules": ["include", "mixin"]
			}
		]
	}
}

如果想实现保存的时候自动修改 可以使用vscode插件-Stylelint 配合在根目录新建.vscode/settings.json

 {
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true,
        "source.fixAll.stylelint": true
    },
    "stylelint.validate": [
        "css",
        "less",
        "postcss",
        "scss",
        "vue"
    ]
}

这里踩坑很久 stylelint迟迟不生效 后来发现是打开路径时候问题

目录结构project\vite-project

我是vscode进入project然后cd到vite-project 这样stylelint迟迟不生效

换为直接打开project\vite-project就好了

创建.stylelintignore文件

dist/
node_modules/

配置环境变量

在根目录下新建.env.local .env.test .env.production 分别为本地开发环境 测试环境 生产环境

.env.test

#test测试环境
NODE_ENV = test
# app api 接口请求地址
VITE_APP_API_BASEURL = https://test-xxx-api.com/
# 企业微信 api 接口请求地址
VITE_APP_API_SCRM = https://test-yyy-api.com/
# 是否在打包时生成 sourcemap
VITE_BUILD_SOURCEMAP = true
# 是否在打包时删除 console 代码
VITE_BUILD_DROP_CONSOLE = false

.env.production

# 正式环境
NODE_ENV = production
# app api 接口请求地址
VITE_APP_API_BASEURL = https://xxx-api.com/
# 企业微信 api 接口请求地址
VITE_APP_API_SCRM = https://yyy-api.com/
# 是否在打包时生成 sourcemap
VITE_BUILD_SOURCEMAP = false
# 是否在打包时删除 console 代码
VITE_BUILD_DROP_CONSOLE = true

引入Axios

安装

npm i axios qs --save

初始化

新建文件src/api/index.js

import axios from 'axios'
import { Toast  } from 'vant'
// 根据url确定baseURL地址
const env = import.meta.env 
const api = axios.create({
    baseURL: env.VITE_APP_API_BASEURL,
    timeout: 10000,
    responseType: 'json'
})

api.interceptors.request.use(
    request => {  // 请求拦截
        return request
    }
)

api.interceptors.response.use(
    response => { // 返回拦截
        if (response.data.code === 10000) {
            return Promise.resolve(response.data)
        } else {
            if (response.data.message) {
                Toast(response.data.message)
            }
        }
    },
    error => {
        return Promise.reject(error)
    }
)

export default api

/**
 * get方法,对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
    return new Promise((resolve, reject) => {
        api.get(url, {
            params: params
        }).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err.data)
        })
    })
}
/**
 * post方法,对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params, headers) {
    return new Promise((resolve, reject) => {
        api.post(url, params, headers).then(res => {
            resolve(res.data)
        }).catch(err => {
            reject(err.data)
        })
    })
}

使用

新建文件src/api/app/index.js

import { get } from '@/api'
export const getProductDetail = data => { return get('/app/ssss', data) }

使用到的插件

1.unplugin-auto-import/vite

自动引入 解决setup需要手动引入ref reactive等

npm i unplugin-auto-import -D --save

vite.config.js

import AutoImport from 'unplugin-auto-import/vite
export default defineConfig({
    plugins: [
      AutoImport({
        imports: [
            'vue',
            'vue-router'
        ],
        dts: false
      })
    ]
})

2.plugin-legacy

低版本浏览器兼容插件,起初没有引入这个插件,因为在开发的时候,打包完毕的页面能在我的手机上正常显示,可是到了测试阶段在个别测试机(Android8.1)上就是空白页,所以引入此模块

npm i @vitejs/plugin-legacy  -D
import legacy from '@vitejs/plugin-legacy'
export default defineConfig({
    plugins: [
      legacy({
         targets: ['ie>=11'],
         additionalLegacyPolyfills: ['regenerator-runtime/runtime']
      })
    ]
})

总结

之前一直用的vue2,所以打算用vue3学习下,从开始到部署上线,各种踩坑但学到了很多,至于状态管理模块暂时还没用得到,用到了打算用Pinia了,等用到了就更新此文章。