Vant的按需引入

1,446 阅读1分钟

一、自动按需引入组件

**1.首先安装 babel-plugin-import 插件 **

npm install babel-plugin-import --save

在这里插入图片描述

按需使用

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
	<!-- 按钮 -->
	<van-button type="warning">警告按钮</van-button>
	<van-button type="danger">危险按钮</van-button>
	<!--  SwitchCell 开关单元格-->
	<van-cell-group>
		<van-switch-cell v-model="checked" title="标题" />
	</van-cell-group>
  </div>
</template>

<script>
(a)  import Vue from 'vue'; //也可以不使用这个(a)(b)形式挂载,
                             //但下面export中要用components挂载每个组件
	//按钮
	import { Button } from 'vant'; //引入组件
(b)   Vue.use(Button); 

	//SwitchCell 开关单元格
	import { SwitchCell } from 'vant';(b)   Vue.use(SwitchCell);

	import { Cell, CellGroup } from 'vant';
(b)   Vue.use(Cell).use(CellGroup);

export default {
	data(){
		return{
			msg:'你好vue!!!',
			checked: true,
		}
	}
}
</script> 

二、手动按需引入组件(不使用插件的情况下)

//引入组件和样式
import Button from 'vant/lib/button';
import 'vant/lib/button/style';

//挂载组件
components:{
	'van-button':Button,
	'van-switch-cell':switchCell,
	'van-cell-group':cellGroup
}

//使用组件
<!-- 按钮 -->
	<van-button type="warning">警告按钮</van-button>
	<van-button type="danger">危险按钮</van-button>

完整代码如下

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
	<!-- 按钮 -->
	<van-button type="warning">警告按钮</van-button>
	<van-button type="danger">危险按钮</van-button>
	<!--  SwitchCell 开关单元格-->
	<van-cell-group>
		<van-switch-cell v-model="checked" title="标题" />
	</van-cell-group>
  </div>
</template>

<script>
	//按钮
	import Button from 'vant/lib/button';
	import 'vant/lib/button/style';

	//SwitchCell 开关单元格
	import switchCell from 'vant/lib/switch-cell';
	import 'vant/lib/switch-cell/style';

	//cell-group
	import cellGroup from 'vant/lib/cell-group';
	import 'vant/lib/cell-group/style';
export default {
	data(){
		return{
			msg:'你好vue!!!',
			checked: true,
		}
	},
	components:{
		'van-button':Button,
		'van-switch-cell':switchCell,
		'van-cell-group':cellGroup
	}
        //不使用components也可以,
        //只需上面import Vue from 'vue';import { Cell, CellGroup } from 'vant';和Vue.use(Cell).use(CellGroup);
}
</script>

总结:

插件自动引入不需要引入每个组件样式,通过插件配置会自动引入样式。

手动引入需要自己引入每个组件的样式。

参考链接:www.freesion.com/article/812…