Vue2-vant按需映入

在根目录下新建vue.config.js文件配置跨域多环境变量,路由懒加载,配置别名等...

先说下vant按需引入


  • -S 就是--save 将插件安装到生产环境 在package,json中的dependencies 打包会打包到dist中,就是上线也需要用
  • -D就是dev将插件安装到开发环境 devDependencies
  • 配路由官方推荐首字母大写且两个单词驼峰命名法

1.下载vant

// Vue 2 项目,安装 Vant 2:
npm i vant -S

// Vue 3 项目,安装 Vant 3:
npm i vant@next -S

// 通过 yarn 安装
yarn add vant

2.下载所需插件

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

3.在babel.config.js配置

// 在.babelrc 中添加配置
// 注意:webpack 1 无需设置 libraryDirectory
{
  "plugins": [
    ["import", {
      "libraryName": "vant",
      "libraryDirectory": "es",
      "style": true
    }]
  ]
}

// 对于使用 babel7 的用户,可以在 babel.config.js 中配置
module.exports = {
  plugins: [
    ['import', {
      libraryName: 'vant',
      libraryDirectory: 'es',
      style: true
    }, 'vant']
  ]
};

4.在页面注册使用

分为页面注册组件使用,和全局按需引入使用

<template>
  <div class="home">
    <Button type="default">默认按钮</Button>
    <Button loading type="primary" loading-type="spinner" />
  </div>
</template>

<script>
import { Button } from 'vant'

export default {
  name: 'home',
  components: {
    Button
  }
}
</script>

4.1 全局使用按需引入

在根目录下新建plugins文件,里面新建index.j(名字自己取,如果不引入其他就index就可以)

在该文件中做引入操作,最后将这个文件在man.js内引入

//plugins/index.js

import Vue from 'vue'
// 在这里引入你所需的组件就可以
import {
  Button,
  Slider
} from 'vant'

// 按需使用组件
Vue.use(Button)
Vue.use(Slider)

export default Vue
//main.js

import Vue from 'vue'
import App from './App.vue'
import '@/plugins'

// 其他操作...

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

5.在页面正常使用

<template>
  <div class="home">
    <van-button type="default">默认按钮</van-button>
     <van-slider v-model="value" @change="onChange" />
  </div>
</template>


<script>
//注意其他的不需要引入,但Toast需要在当前使用的页面使用
import { Toast  } from "vant";
export default {
  data() {
    return {
    value: 50,
    };
  },
  methods: {  
     onChange(value) {
      Toast('当前值:' + value);
    },
  },
 
};
</script>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

彩色之外

你的打赏是我创作的氮气加速动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值