1.vue3-vant-h5-template移動(dòng)端模板

1.創(chuàng)建項(xiàng)目

創(chuàng)建項(xiàng)目之前首先確保你安裝了最新版本的 Node.js

image.png

創(chuàng)建項(xiàng)目,在命令行中運(yùn)行以下命令

npm init vue@latest
image.png

執(zhí)行如下命令進(jìn)入項(xiàng)目更目錄并按照依賴

cd vue3-vant-h5-template
npm install
image.png

執(zhí)行下面命令運(yùn)行項(xiàng)目

npm run dev
image.png

2.安裝vant

vant官網(wǎng):https://vant-contrib.gitee.io/vant/#/zh-CN

image.png

2.1在現(xiàn)有項(xiàng)目中使用 Vant 時(shí),可以通過 npm 進(jìn)行安裝:

# Vue 3 項(xiàng)目,安裝最新版 Vant
npm i vant --save

2.2按需引入組件

在基于 vite 的項(xiàng)目中使用 Vant 時(shí),可以使用 unplugin-vue-components 插件,它可以自動(dòng)引入組件,并按需引入組件的樣式。

安裝插件

# 通過 npm 安裝
npm i unplugin-vue-components -D

配置插件

如果是基于 vite 的項(xiàng)目,在 vite.config.js 文件中配置插件:

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    Components({
      resolvers:[VantResolver()]
    })
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})

使用組件

完成以上兩步,就可以直接在模板中使用 Vant 組件了,unplugin-vue-components 會(huì)解析模板并自動(dòng)注冊(cè)對(duì)應(yīng)的組件。

<template>
  <van-button type="primary" />
</template>

引入函數(shù)組件的樣式

Vant 中有個(gè)別組件是以函數(shù)的形式提供的,包括 Toast,Dialog,Notify 和 ImagePreview 組件。在使用函數(shù)組件時(shí),unplugin-vue-components 無法自動(dòng)引入對(duì)應(yīng)的樣式,因此需要手動(dòng)引入樣式。

// main.ts
import { createApp } from "vue";
import App from "./App.vue";

import "./assets/main.css";

//引入vant中函數(shù)式組件的樣式
// Toast
import "vant/es/toast/style";
// Dialog
import "vant/es/dialog/style";
// Notify
import "vant/es/notify/style";
// ImagePreview
import "vant/es/image-preview/style";


createApp(App).mount("#app");

你可以在項(xiàng)目的入口文件或公共模塊中引入以上組件的樣式,這樣在業(yè)務(wù)代碼中使用組件時(shí),便不再需要重復(fù)引入樣式了。

// ./src/components/HelloWorld.vue
<script setup lang="ts">
import { showToast, showDialog, showNotify, showImagePreview } from "vant";

defineProps<{
  msg: string;
}>();

const testShowToast = () => {
  showToast("測(cè)試showToast");
};
const testShowDialog = () => {
  showDialog({ message: "測(cè)試showDialog" });
};
const testShowNotify = () => {
  showNotify({ message: "測(cè)試showNotify" });
};
const testShowImagePreview = () => {
  showImagePreview(['https://fastly.jsdelivr.net/npm/@vant/assets/apple-1.jpeg']);
};
</script>

<template>
  <div>
    <van-button type="primary" @click="testShowToast">showToast</van-button>
    <van-button type="success" @click="testShowDialog">showDialog</van-button>
    <van-button type="default" @click="testShowNotify">showNotify</van-button>
    <van-button type="warning" @click="testShowImagePreview">showImagePreview</van-button>
  </div>
</template>

<style scoped>
</style>

3.瀏覽器適配

Viewport 布局

Vant 默認(rèn)使用 px 作為樣式單位,如果需要使用 viewport 單位 (vw, vh, vmin, vmax),推薦使用 postcss-px-to-viewport 進(jìn)行轉(zhuǎn)換。

postcss-px-to-viewport 是一款 PostCSS 插件,用于將 px 單位轉(zhuǎn)化為 vw/vh 單位。

3.1安裝

npm install postcss-px-to-viewport -D

3.2在項(xiàng)目根目錄下添加postcss.config.js文件

// postcss.config.js
module.exports = {
  plugins: {
    'postcss-px-to-viewport': {
      viewportWidth: 375,
    },
  },
};

Tips: 在配置 postcss-loader 時(shí),應(yīng)避免 ignore node_modules 目錄,否則將導(dǎo)致 Vant 樣式無法被編譯。

別急,你以為就這樣完事了嗎,并沒有。上面只是對(duì)設(shè)計(jì)稿尺寸為 375 的進(jìn)行轉(zhuǎn)換( vant 設(shè)計(jì)稿尺寸是 375 ??♂?),但是我們大部分設(shè)計(jì)稿尺寸都是 750 ,所以需要額外對(duì) 750 尺寸的進(jìn)行處理。
由于 postcss-px-to-viewport 沒有提供類似 postcss-pxtorem 中 rootValue({ file }) {} 的方法,即便使用 module.exports = (param) => {} 這種方式導(dǎo)出postcss配置,也拿不到當(dāng)前轉(zhuǎn)換文件的信息(備注:以前我記得是可以拿到的,現(xiàn)在拿不到了),所以無法根據(jù)文件路徑動(dòng)態(tài)設(shè)置 viewportWidth,
有一種hack方式:通過多次 pxToViewport() 處理不同文件來設(shè)置viewportWidth??

// postcss.config.js
const path = require('path');
const pxToViewport = require('postcss-px-to-viewport');
module.exports = {
  plugins: [
    pxToViewport({ // vant
      viewportWidth: 375,
      propList: ["*"], // 指定轉(zhuǎn)換的css屬性的單位,*代表全部css屬性的單位都進(jìn)行轉(zhuǎn)換
      selectorBlackList: ['aaaa'],// 指定不轉(zhuǎn)換為視窗單位的類名,
      exclude: [/^(?!.*node_modules\/vant)/],// 設(shè)置忽略文件,用正則做目錄名匹配
      //include: [/node_modules\/vant/],
    }),
    pxToViewport({ // 非vant
      viewportWidth: 750,
      exclude: [/node_modules\/vant/],
    })
  ]
}

第一個(gè)處理 vant 的 pxToviewport 為什么不用include選項(xiàng)呢?

因?yàn)?postcss-px-to-viewport v1.1.1 不支持 include 配置項(xiàng),v1.2.0 開始加入include,但是并沒有發(fā)布到npm倉(cāng)庫(kù)??♂?,
然后運(yùn)行項(xiàng)目,你會(huì)發(fā)現(xiàn)報(bào)如下警告:


bb5224bc4782023d86e9681d7ddaec5.png

原因是 postcss-px-to-viewport 不支持 postcss 8.x ,而vite內(nèi)置postcss 8.x,所以使用postcss-px-to-viewport會(huì)拋出警告??♂?

要改用 postcss-px-to-viewport-8-plugin(https://github.com/lkxian888/postcss-px-to-viewport-8-plugin) 替代,既支持 include 配置項(xiàng),也支持postcss 8.x

image.png
image.png

安裝:

npm install postcss-px-to-viewport-8-plugin -D

最終完整的postcss.config.js代碼為:

// postcss.config.js
const path = require('path');
const pxToViewport = require('postcss-px-to-viewport-8-plugin');
module.exports = {
  plugins: [
    pxToViewport({ // vant
      viewportWidth: 375,
      propList: ["*"], // 指定轉(zhuǎn)換的css屬性的單位,*代表全部css屬性的單位都進(jìn)行轉(zhuǎn)換
      selectorBlackList: ['aaaa'],// 指定不轉(zhuǎn)換為視窗單位的類名,
      exclude: [/^(?!.*node_modules\/vant)/],// 設(shè)置忽略文件,用正則做目錄名匹配
    }),
    pxToViewport({ // 非vant
      viewportWidth: 750,
      exclude: [/node_modules\/vant/],
    })
  ]
}

4.自動(dòng)添加前綴

autoprefixer是一款自動(dòng)管理瀏覽器前綴的插件,它可以解析CSS文件并且添加瀏覽器前綴到CSS內(nèi)容里,使用Can I Use(caniuse網(wǎng)站)的數(shù)據(jù)來決定哪些前綴是需要的

安裝

npm i autoprefixer -D

在postcss.config.js中配置

// postcss.config.js
const autoprefixer = require('autoprefixer');
const pxToViewport = require('postcss-px-to-viewport-8-plugin');
module.exports = {
  plugins: [
    autoprefixer({
      overrideBrowserslist: ['Android 4.1', 'iOS 7.1', 'Chrome > 35', 'ff > 31', 'ie >= 8']
    }), // 自動(dòng)為css添加瀏覽器前綴
    pxToViewport({ // vant
      viewportWidth: 375,
      propList: ["*"], // 指定轉(zhuǎn)換的css屬性的單位,*代表全部css屬性的單位都進(jìn)行轉(zhuǎn)換
      selectorBlackList: ['aaaa'],// 指定不轉(zhuǎn)換為視窗單位的類名,
      exclude: [/^(?!.*node_modules\/vant)/],// 設(shè)置忽略文件,用正則做目錄名匹配
    }),
    pxToViewport({ // 非vant
      viewportWidth: 750,
      exclude: [/node_modules\/vant/],
    })
  ]
}

5.CSS 預(yù)處理器less

安裝

npm install less -D

安裝后直接使用就可以啦


image.png

6.項(xiàng)目規(guī)范

6.1集成editorconfig配置

EditorConfig 有助于為不同 IDE 編輯器上處理同一項(xiàng)目的多個(gè)開發(fā)人員維護(hù)一致的編碼風(fēng)格。

在項(xiàng)目根目錄創(chuàng)建.editorconfig文件

# http://editorconfig.org

root = true

[*] # 表示所有文件適用
charset = utf-8 # 設(shè)置文件字符集為 utf-8
indent_style = space # 縮進(jìn)風(fēng)格(tab | space)
indent_size = 2 # 縮進(jìn)大小
end_of_line = lf # 控制換行類型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行首的任意空白字符
insert_final_newline = true # 始終在文件末尾插入一個(gè)新行

[*.md] # 表示僅 md 文件適用以下規(guī)則
max_line_length = off
trim_trailing_whitespace = false

VSCode需要安裝一個(gè)插件:EditorConfig for VS Code


image.png

6.2. 使用prettier工具(不需要做,創(chuàng)建項(xiàng)目時(shí)自動(dòng)安裝了prettier并生成了配置文件)

Prettier 是一款強(qiáng)大的代碼格式化工具,支持 JavaScript、TypeScript、CSS、SCSS、Less、JSX、Angular、Vue、GraphQL、JSON、Markdown 等語(yǔ)言,基本上前端能用到的文件格式它都可以搞定,是當(dāng)下最流行的代碼格式化工具。

1.安裝prettier

npm install prettier -D

2.在項(xiàng)目根目錄創(chuàng)建.prettierrc文件并配置:

  • useTabs:使用tab縮進(jìn)還是空格縮進(jìn),選擇false;

  • tabWidth:tab是空格的情況下,是幾個(gè)空格,選擇2個(gè);

  • printWidth:當(dāng)行字符的長(zhǎng)度,推薦80,也有人喜歡100或者120;

  • singleQuote:使用單引號(hào)還是雙引號(hào),選擇true,使用單引號(hào);

  • trailingComma:在多行輸入的尾逗號(hào)是否添加,設(shè)置為 none;

  • semi:語(yǔ)句末尾是否要加分號(hào),默認(rèn)值true,選擇false表示不加;

{
  "useTabs": false,
  "tabWidth": 2,
  "printWidth": 80,
  "singleQuote": true,
  "trailingComma": "none",
  "semi": false
}

3.創(chuàng)建.prettierignore忽略文件

/dist/*
.local
.output.js
/node_modules/**

**/*.svg
**/*.sh

/public/*

4.VSCode需要安裝prettier的插件

image.png

5.測(cè)試prettier是否生效

  • 測(cè)試一:在代碼中保存代碼;

  • 測(cè)試二:配置一次性修改的命令;

在package.json中配置一個(gè)scripts:

    "prettier": "prettier --write ."

一次性格式化所有編寫的js代碼,執(zhí)行npm run prettier

而我們按照之前命令創(chuàng)建項(xiàng)目時(shí)其實(shí)已經(jīng)安裝了prettier,并且在package.json中自動(dòng)添加了用來格式化代碼的腳本,也自動(dòng)創(chuàng)建了.prettierrc.json文件


image.png

image.png

6.3. 使用ESLint檢測(cè)

1.在前面創(chuàng)建項(xiàng)目的時(shí)候,我們就選擇了ESLint,所以Vue會(huì)默認(rèn)幫助我們配置需要的ESLint環(huán)境。

2.VSCode需要安裝ESLint插件:

image.png

————————————————
版權(quán)聲明:本文參考CSDN博主「小滿只想睡覺」的原創(chuàng)文章,鏈接:https://blog.csdn.net/xxxzzzqqq_/article/details/129554703

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容