在根目录下新建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>
更新中...