Vant 组件库的安装、按需引入、全局引入及样式修改

目录

1. 下载安装

2. 全局引入:在main.js文件内引入

3. 按需引入:在main.js文件内引入 ( 推荐 )

4. 手动按需引入组件:在使用组件的页面内引入

5. 引入其他内容:(依据项目需求进行配置)

6. 修改组件原来样式:


1. 下载安装

  1.1  安装Vant:

      Vue 3 项目,安装最新版 Vant: npm i vant -S

      Vue 2 项目,安装 Vant 2: npm i vant@latest-v2 -S

  1.2  安装插件:yarn add babel-plugin-import -D (babel.config.js配置文件)

扫描二维码关注公众号,回复: 16515705 查看本文章
module.exports = {
  plugins: [
    ['import', {
      libraryName: 'vant',
      libraryDirectory: 'es',
      style: true
    }, 'vant']
  ]
};

  1.3  postcss.config.js配置文件进行适配:

module.exports = {
  plugins: {
    "postcss-pxtorem": {
      rootValue({ file }) {
        return file.indexOf("vant") !== -1 ? 37.5 : 75;
      },
      propList: ["*"],
    },
  },
};

2. 全局引入:在main.js文件内引入

import Vue from 'vue';
import Vant from 'vant';
import 'vant/lib/index.css';

Vue.use(Vant);

3. 按需引入:在main.js文件内引入 ( 推荐 )

import Vue from "vue";
import App from "./App.vue";
import "vant/lib/index.css";
import { Form, Field, Button, List, Icon, Toast } from "vant"; // 按需引入,优化加载速度

Vue.use(Form);
Vue.use(Field);
Vue.use(Button);
Vue.use(List);
Vue.use(Icon);
Vue.use(Toast);

4. 按需引入组件:在使用组件的页面内引入

手动按需引入
1. 引入:
     import Button from 'vant/lib/button'; // button组件
     import 'vant/lib/button/style';               // button样式
2. 注册:
export default {
    components: { // 手动注册组件名
        VanButton: Button  //注册大驼峰,使用写短横线
       === //[Button.name]: Button
 }}
3. 使用:
<van-button type="primary">主要按钮</van-button>
自动按需引入:
1. 安装插件:yarn add babel-plugin-import -D
2. 在babel配置文件里 (babel.config.js):
module.exports = {
  plugins: [
    ['import', {
      libraryName: 'vant',
      libraryDirectory: 'es',
      style: true
    }, 'vant']]}
3. 全局注册 - 会自动按需引入
import { Button } from 'vant';
Vue.use(Button)

5. 引入其他内容:(依据项目需求进行配置)

import router from "./router"; // 路由对象
import "@/mobile/flexible"; // 适配,当网页宽度改变, 会修改html的font-size
import "vant/lib/index.css"; // vant组件样式
import "./assets/common.less"; // 引入公共样式
import "amfe-flexible"; // 页面适配,动态设置 REM 基准值
import "@vant/touch-emulator"; // 桌面端将mouse事件转换成touch事件
... ... (导入的vant组件)

Vue.config.productionTip = false;

new Vue({
  router,
  render: (h) => h(App),
}).$mount("#app");

6. 修改组件原来样式:

方法一:通过谷歌调试工具找到当前类名,::v-deep样式穿透进行修改(没有下载less的话不能进行样式嵌套)

::v-deep {
  .van-field__label {
    display: flex;
    justify-content: end;
    align-items: center;
  }
  .van-nav-bar {
    background-color: #1989fa;
  }
  .van-nav-bar__title {
    color: #fff;
  }
}

方法二:给标签手动添加 class 类名进行修改,class = 'tab'

.tab {
   display: flex;
   justify-content: end;
   align-items: center;
}

猜你喜欢

转载自blog.csdn.net/m0_61663332/article/details/128441091