Vue组件
动态组件 <component>
-
功能 :渲染一个"元组件"为动态组件。依
is
的值,来决定哪个组件被渲染。 -
平台差异说明:
平台 支持情况 App √ (Vue2 需传入 String 类型) HarmonyOS Next HBuilderX 4.24 H5 √ 微信小程序/支付宝小程序/百度小程序/抖音小程序等 x
条件渲染和列表渲染 <template>
和 <block>
-
功能:用于条件渲染或列表渲染。它们不是真正的组件,而是包装元素,不会在页面中做任何渲染,只接受控制属性。
-
平台差异说明:
平台 支持情况 App/HarmonyOS Next/H5/微信小程序/支付宝小程序/百度小程序/抖音小程序/QQ小程序等 基本上所有平台都支持 <template>
;部分平台不建议使用<block>
示例
html
<template>
<view>
<template v-if="test">
<view>test 为 true 时显示</view>
</template>
<template v-else>
<view>test 为 false 时显示</view>
</template>
</view>
</template>
过渡效果 <transition>
和 <transition-group>
- 功能:提供单个或多个元素/组件的过渡效果。
- 平台差异说明 :
<transition>
: 主要在 H5 平台上支持。<transition-group>
: 同样主要在 H5 平台上支持。
示例
html
<transition name="fade">
<div v-show="show">这是一段会淡入淡出的文字。</div>
</transition>
缓存组件 <keep-alive>
- 功能:包裹动态组件时,缓存不活动的组件实例而不是销毁它们。
- 平台差异说明:主要在 H5 平台上支持。
内容分发 <slot>
- 功能:作为组件模板之中的内容分发插槽。
- 平台差异说明 :几乎所有平台都支持
<slot>
。
示例
html
<my-component>
<template v-slot:default>
<p>默认插槽内容</p>
</template>
</my-component>
uniapp组件使用差异
组件命名规则
在 Vue 中注册组件时,需要为其指定一个名称。定义组件名的方式有两种:
Kebab-case(短横线分隔命名)
- 定义:使用短横线分隔单词来命名组件。
- 引用 :当使用此方式定义组件时,必须以相同的方式引用该组件,例如
<my-component-name>
。
PascalCase(首字母大写命名)
- 定义:使用首字母大写的命名方式定义组件。
- 引用 :可以使用两种方式引用该组件,即
<my-component-name>
和<MyComponentName>
都是可接受的。
组件目录结构
在 UniApp 工程中,自定义组件应存放在根目录下的 components
文件夹内,并遵循以下目录结构:
│─components
│ └─componentA
│ └─componentA.vue // 可复用的 componentA 组件
│ └─component-a.vue // 可复用的 component-a 组件
全局注册
- 在
main.js
中引入并全局注册组件。 - 注册后,该组件可在所有页面中直接使用。
javascript
import App from './App'
import { createSSRApp } from 'vue'
import myComponent from './components/my-component/my-component.vue'
export function createApp() {
const app = createSSRApp(App)
app.component('my-component', myComponent) // 全局注册组件
return { app }
}
注意事项
app.component
的第一个参数必须是静态字符串。.nvue
页面暂不支持全局组件。
局部注册
传统方法
- 在需要使用的页面通过
import
引入组件。 - 在
components
选项中注册该组件。
html
<template>
<view>
<uni-badge text="1"></uni-badge>
</view>
</template>
<script>
import uniBadge from '@/components/uni-badge/uni-badge.vue';
export default {
components: { uniBadge }
}
</script>
Easycom 方式
- 符合
components/组件名称/组件名称.vue
目录结构的组件可以直接使用,无需导入和注册。
html
<template>
<view>
<uni-badge text="1"></uni-badge>
</view>
</template>
<script>
export default {}
</script>
Easycom 特性
- 自动开启,不需要手动配置。
- 支持个性化设置,在
pages.json
的easycom
节点进行配置。 - 打包时会自动剔除未使用的组件,优化了性能。
UniApp 插件市场
- 提供丰富的现成组件,符合
components/组件名称/组件名称.vue
结构的组件可以直接使用。
注意事项
- UniApp 仅支持
.vue
单文件组件。 - 动态组件、自定义 render 和
<script type="text/x-template">
字符串模板等特性在非 H5 端不被支持。