uniapp usingcomponents 怎么配置
时间: 2023-08-12 20:03:30 浏览: 261
在 uni-app 中,使用 `components` 时需要在 `pages.json` 文件中配置 `usingComponents` 字段。`usingComponents` 字段用来声明在这个页面中要使用的自定义组件,可以是全局注册的组件,也可以是局部注册的组件。
例如,在 `pages/index/index.vue` 页面中,我们要使用一个名为 `my-component` 的自定义组件,可以在 `pages.json` 文件中添加以下配置:
```json
{
"pages": [
{
"path": "pages/index/index",
"usingComponents": {
"my-component": "/components/my-component/index"
}
}
]
}
```
在上面的配置中,我们将 `my-component` 组件的路径设置为 `/components/my-component/index`,这表示 `my-component` 组件的定义文件在 `components/my-component/index.vue` 中。
之后,在 `pages/index/index.vue` 页面中就可以直接使用 `my-component` 组件了:
```vue
<template>
<div>
<my-component></my-component>
</div>
</template>
```
在 `pages.json` 文件中可以配置多个页面,每个页面都可以声明自己要使用的自定义组件。
需要注意的是,如果使用的是 npm 包中的组件,在 `usingComponents` 中的路径应该使用 `npm://` 前缀,例如:
```json
{
"pages": [
{
"path": "pages/index/index",
"usingComponents": {
"my-component": "npm://my-component"
}
}
]
}
```
在上面的配置中,我们使用 `npm://` 前缀来表示 `my-component` 组件是从 npm 包中引入的。实际使用时,需要将 `npm://` 替换为 `/@npm/`,例如:
```json
{
"pages": [
{
"path": "pages/index/index",
"usingComponents": {
"my-component": "/@npm/my-component"
}
}
]
}
```