Taro 引入 vant

一、clone Vant-weapp 源码到本地

git clone https://github.com/youzan/vant-weapp.git

二、将dist目录下的文件拷贝至 /src/components/vant-weapp

Taro 引入 vant_第1张图片

三、修改 /src/config/index.js

const createVantPatterns = (componentName) => {
	const fileTypes = ['wxml', 'wxs', 'wxss'];
	return fileTypes.map((item) => {
		return {
			from: `src/components/vant-weapp/${componentName}/index.${item}`,
			to: `dist/components/vant-weapp/${componentName}/index.${item}`
		};
	});
};

const config = {
	...
	copy: {
		patterns: [
			/** 此处为公共组件,必需--start */
			{
				from: 'src/components/vant-weapp/wxs',
				to: 'dist/components/vant-weapp/wxs'
			},
			{
				from: 'src/components/vant-weapp/common/style',
				to: 'dist/components/vant-weapp/common/style'
			},
			{
				from: 'src/components/vant-weapp/common/index.wxss',
				to: 'dist/components/vant-weapp/common/index.wxss'
			},
			/** 此处为公共组件,必需--end */
			// 以下为按需引入的组件,要注意各组件的依赖组件也得引入
			{
				from: 'src/components/vant-weapp/area-data/index.js',  // 省市区联动的数据
				to: 'dist/components/vant-weapp/area-data/index.js'
			},
			...createVantPatterns('button'),
			...createVantPatterns('icon'),
			...createVantPatterns('info'),
			...createVantPatterns('area'),
			...createVantPatterns('picker'),
			...createVantPatterns('picker-column'),
			...createVantPatterns('popup'),
			...createVantPatterns('overlay'),
			...createVantPatterns('transition'),
			...createVantPatterns('loading')
		],
		...
		mini: {
			postcss: {
				...
				pxtransform: {
					enable: true,
					config: {
						selectorBlackList: [/van-/]  // 禁止转换Vant的样式
					}
				}
			}
		}
	}
};

四、引入Vant组件

1、局部引入:

export default definePageConfig({
	usingComponents: {
		'van-button': '@vant/button/index',
		'van-area': '@vant/area/index',
		'van-popup': '@vant/popup/index'
	}
});

2、使用组件

<van-button
	type="primary"
	@tap="showArea = true;"
>
	按钮
van-button>

可能会遇到的坑及解决方案:
(1)子组件内引用不生效:需要在外层父组件中引用。(建议在app.config.js中全局引入)
(2) 更改vant组件的样式时,可能会出现px无法被编译为rpx的情况:直接在css中使用rpx单位。

你可能感兴趣的:(H5,taro,前端,javascript)