最近,很多人给我留言,问我说怎么在mpvue项目中引入小程序原生框架中的自定义组件。
有这种需求,是非常正常的一件事情。因为在实际开发中,我们通常希望使用已有的开源组件库来进行开发,这些开源组件库大多是基于原生自定义组件的方式写成,比如目前比较流行的Vant Weapp、iView Weapp等等。所以,在mpvue项目中如何引入并使用这些自定义组件,就成了必须了解的一个问题。
有些朋友在自己尝试的过程中遇到了挺多的问题,那就让我来告诉你们经过我实测后认为的正确使用方式吧。
步骤一:生成你的mpvue工程
通过vue-cli命令,我们先生成一个全新的mpvue工程代码:
vue init mpvue/mpvue-quickstart my-project
然后进入该工程目录,通过npm安装依赖:
cd my-project
npm install
步骤二:下载小程序组件库
小程序的组件库有挺多,我们这里选用iVew Weapp作为示例。你可以直接去github把iView Weapp的代码下载下来,也可以用过npm来下载:
npm i iview-weapp
下载完成后,到它的目录中寻找名为dist的目录,这里面存放的就是iView Weapp原生小程序自定义组件代码。
步骤三:将组件库复制到工程的static目录下
你可以将上面提到的整个dist目录复制到你的mpvue工程下的static目录下(记得一定要是static目录,否则这些代码会被mpvue编译器错误的进行处理),然后给这个dist目录改个名字,比如叫iview。

步骤四:为需要使用自定义组件的Page进行配置
我们知道,原生小程序开发中,我们如果要在Page中使用自定义的组件,则需要在该Page对应的.json
配置文件中配置要使用的自定义组件。在mpvue中,我们也需要做等价的配置。
比如,现在我要在src/pages/index/index.vue
中使用iView中的i-button
组件,那么就先要在src/pages/index/main.json
(如果没有该文件,则新建一个)中进行如下配置:
{
"usingComponents": {
"i-button": "../../../static/iview/button/index"
}
}
步骤五:在Page中使用自定义组件
经过上一步的配置,我们就可以开始在src/pages/index/index.vue
中使用这个i-button
组件了,就像这样:
<template>
<div class="container">
<i-button type="primary" @click="bindViewTap">这是一个按钮</i-button>
</div>
</template>
运行这个小程序,能看到如下的样子:

怎么样?很简单吧!快试试吧。
网友评论
运行提示vue不是不是内部或外部命令,也不是可运行的程序
或批处理文件。加了PATH,也不管用,怎么回事?
main.json 中代码:"usingComponents": {
"i-button": "../../static/iview/button/index"
}
iview 的目录放在了static/。
请大神指导
{
"usingComponents": {
"i-toast": "../../../static/iview/toast/index"
}
}
因为目前看来没有办法对小程序自定义组件做全局引入。。。
但引入toast 这样需要js 主动调用的 就会出问题,不知道有没有碰到过呢?
重现步骤:
```
<template>
<div class="container">
<i-button type="ghost" @click="handleText">只显示文本</i-button>
<i-toast id="toast"/>
</div>
</template>
<script>
const {$Toast} = require('../../../static/iview/base/index');
console.info($Toast);
export default {
data() {
return {}
},
methods: {
handleText() {
$Toast({content: '这是文本提示'});
}
},
created() {
}
}
</script>
<style scoped>
</style>
```
会有如下错误:
无法找到对应的组件,请按文档说明使用组件
Cannot read property 'handleShow' of null; [Component] Event Handler Error @ pages/index/main#bound handleProxy
TypeError: Cannot read property 'handleShow' of null
const componentCtx = ctx.selectComponent(selector);
if (!componentCtx) {
console.error('无法找到对应的组件,请按文档说明使用组件');
return null;
}
selectComponent 没有获取到东西
请帮看一下这个问题,非常感谢
{
"usingComponents": {
"i-toast": "../../../static/iview/toast/index"
}
}
"usingComponents": {
"i-button": "../../../static/iview/button/index"
}
}
要放在main.json,请问能在main.js这样写吗export default {
config: {
"usingComponents": {
"i-button": "../../../static/iview/button/index"
}
}
}