最近項目用到了vue和vant踪栋,以及自定義vant主題,記錄主要步驟點(diǎn)如下:
1、首先需要全局安裝vue-cli:
npm install -g @vue/cli
2复唤、創(chuàng)建vue項目
vue create my-app
你會被提示選取一個 preset。你可以選默認(rèn)的包含了基本的 Babel + ESLint 設(shè)置的 preset烛卧,也可以選“手動選擇特性”來選取需要的特性佛纫。這里選擇手動。
? Please pick a preset:
default (babel, eslint)
> Manually select features
回車后選擇以下配置:
? Check the features needed for your project:
(*) Babel
( ) TypeScript
( ) Progressive Web App (PWA) Support
(*) Router
(*) Vuex
>(*) CSS Pre-processors
(*) Linter / Formatter
( ) Unit Testing
( ) E2E Testing
這里的CSS pre-processor 選擇 Less总放。
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter
? Use history mode for router? (Requires proper server setup for index fallback in production) No
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Less
? Pick a linter / formatter config: Standard
? Pick additional lint features: Lint on save
? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
? Save this as a preset for future projects? No
稍等一會呈宇,項目就創(chuàng)建完畢啦。
進(jìn)入項目目錄:
cd my-app
運(yùn)行項目:
npm run serve
打開瀏覽器看到如下界面局雄,vue項目到此就創(chuàng)建成功啦甥啄。
3、安裝Vant
npm i vant -S
package.json中看到vant炬搭,就安裝完成了蜈漓。
4穆桂、引入Vant
這里選擇自動按需引入組件
安裝babel插件
npm i babel-plugin-import -D
在babel.config.js 中配置:
module.exports = {
presets: ['@vue/cli-plugin-babel/preset'],
plugins: [
[
'import',
{
libraryName: 'vant',
libraryDirectory: 'es',
// 指定樣式路徑
style: (name) => `${name}/style/less`
},
'vant'
]
]
}
在main.js中按需引入,如下:
import { Button, Col, Row } from 'vant'
Vue.use(Button)
.use(Col)
.use(Row)
5融虽、自定義Vant主題
src下新建style目錄充尉,新建myvant.less文件用于自定義vant主題樣式。
可以根據(jù)需要修改vant基礎(chǔ)樣式變量衣形,以適應(yīng)項目需求驼侠,這里我改了@red,@blue等顏色谆吴。
也可以修改某個組件的樣式變量倒源。
vue.config.js中配置:
*myvant.less就是自定義主題的less文件。引入less文件句狼,以下兩種方式都可以笋熬。
方式一:
const path = require('path')
module.exports = {
css: {
loaderOptions: {
less: {
// 若 less-loader 版本小于 6.0,請移除 lessOptions 這一級腻菇,直接配置選項胳螟。
modifyVars: {
// 或者可以通過 less 文件覆蓋(文件路徑為絕對路徑)
hack: `true; @import "${path.join(
__dirname,
'./src/style/myvant.less'
)}";`
}
}
}
}
}
方式二:
module.exports = {
css: {
loaderOptions: {
less: {
// 若 less-loader 版本小于 6.0,請移除 lessOptions 這一級筹吐,直接配置選項糖耸。
modifyVars: {
// 或者可以通過 less 文件覆蓋(文件路徑為絕對路徑)
hack: 'true; @import "~@/style/myvant.less"'
}
}
}
}
}
6、查看效果
app.vue中引用組件
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<van-row gutter="20">
<van-col span="8">
<van-button type="primary">主要按鈕</van-button>
</van-col>
</van-row>
<!-- <router-view/> -->
</div>
</template>
可以看到button的背景色丘薛,border-radius已經(jīng)是myvant.less中定義的@green: #33f892;和@button-border-radius: 8px;
接下來就可以按項目需要自由發(fā)揮啦嘉竟。