uniapp components 组件如何引用别的组件
在uniapp中,如何在components组件里引用其他组件?需要具体步骤和代码示例,比如父子组件之间的引用方式,以及是否需要特殊配置。
2 回复
在uni-app中引用组件:
- 在
components目录创建组件。 - 在页面
script中import引入组件。 components选项中注册组件。- 模板中直接使用组件标签。
示例:
import MyComponent from '@/components/MyComponent.vue';
export default {
components: { MyComponent }
}
模板:<my-component />
在 UniApp 中,引用其他组件分为全局引用和局部引用两种方式。以下是具体步骤:
一、全局引用(适用于多个页面频繁使用的组件)
-
在
main.js中注册组件:import myComponent from '@/components/myComponent.vue'; Vue.component('my-component', myComponent); -
在页面中直接使用:
<template> <view> <my-component></my-component> </view> </template>
二、局部引用(适用于特定页面)
-
在页面脚本中导入并注册:
<script> import myComponent from '@/components/myComponent.vue'; export default { components: { 'my-component': myComponent } } </script> -
在模板中使用:
<template> <view> <my-component></my-component> </view> </template>
注意事项:
- 组件路径建议使用
@别名(指向项目根目录的src目录) - 确保组件文件路径正确,
.vue文件需包含必要的<template>、<script>和<style> - 组件名建议使用 kebab-case(短横线命名),如
my-component
示例目录结构:
src/
components/
myComponent.vue
pages/
index/
index.vue
使用局部引用时,在 index.vue 中按上述步骤导入即可。全局引用一次配置后可在所有页面直接使用。

