vue-cli4建立vantUI项目,按需引入,适配Rem,自定义主题

使用vue-cli4建立一个vue项目

//vue-cli@4.2.3
vue create vant-demo

根据本身的须要选择对应的配置,此处略过。。。
PS:由于vantUI使用的是less预处理器,配置时建议选择此处理器。css

安装vantUI,按需引入

安装vantUI

npm i vant -S

按需引入

babel-plugin-import是一款 babel 插件,它会在编译过程当中将 import 的写法自动转换为按需引入的方式vue

npm i babel-plugin-import -D

经过vue-cli4建立项目的时候,因为内部集成了babel,在项目的根目录有babel.config.js文件,在此文件添加配置。git

module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset'
  ],
  plugins: [
    ['import', {
      libraryName: 'vant',
      libraryDirectory: 'es',
      style: true
    }, 'vant']
  ]
}

image.png

main.js引入vantUI组件

由于每一个组件都须要使用Vue.use()注册,能够直接使用Array遍历,由于使用了babel-plugin-import插件,按需引入的方式,因此能够不须要写每一个组件的style。github

import {Button,RadioGroup, Radio} from 'vant'

[Button,RadioGroup,Radio].forEach(e=>{
  Vue.use(e)
})

image.png

在项目中及直接用对应的组件便可vue-cli

image.png

效果:npm

image.png

适配Rem

Vant 中的样式默认使用px做为单位,移动端使用Rem会更好,官方文档推荐使用一下两个工具:babel

分别安装less

npm install postcss-pxtorem -D

npm i amfe-flexible

安装好后,在main.js引入amfe-flexibleide

import  'amfe-flexible/index.js'

image.png

若是项目根目录有postcss.config.js文件直接打开,没有就直接建立一个,在根目录啊,别跑偏了(哈哈)!工具

//postcss.config.js
module.exports = {
    plugins: {
      'autoprefixer': {
        overrideBrowserslist: [
          'Android 4.1',
          'iOS 7.1',
          'Chrome > 31',
          'ff > 31',
          'ie >= 8'
        ]
      },
      'postcss-pxtorem': {
        rootValue: 37.5,
        propList: ['*']
      }
    }
}

image.png

PS:375px 即100%宽度,写px会自动rem处理,若是不想被rem处理,可使用PX来写。

测试一下:

image.png

显示

image.png

自定义主题

Vant 使用了Less对样式进行预处理,并内置了一些样式变量,经过替换样式变量便可定制你本身须要的主题。

下面是一些基本的样式变量,全部可用的颜色变量请参考配置文件

// Component Colors  
@text-color:  #323233; 
@border-color:  #ebedf0;
@active-color:  #f2f3f5; 
@background-color:  #f7f8fa; 
@background-color-light:  #fafafa;

按需引入时,自定义主题

更改babel.config.js文件,因为上面步骤引入了,这里稍微更改点就行

module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset'
  ],
  plugins: [
    ['import', {
      libraryName: 'vant',
      libraryDirectory: 'es',
      // style: true
      style: name => `${name}/style/less`
    }, 'vant']
  ]
}

image.png

根目录建立vue.config.js文件,内容以下:

module.exports = {
    css: {
        loaderOptions: {
            less: {
                modifyVars: {
                    'radio-checked-icon-color': '#f20000',
                }
            }
        }
    }
};

全部可用的颜色变量请参考配置文件

image.png

重启项目

npm run serve

image.png

还能够单独引入一个像是文件,配置主题颜色
新建一个theme.less文件
内容以下:

@radio-checked-icon-color:#00f228;

image.png

修改vue.config.js文件
image.png

重启项目

npm run serve

image.png

所有引入和单独引入style时,自定义主题

引入样式时,要把css改为less

// 引入所有样式  import  'vant/lib/index.less'; 
// 引入单个组件样式  import  'vant/lib/button/style/less';
相关文章
相关标签/搜索