uniapp中的vue组件与组件使用差异

/ 前端

Vue组件

动态组件 <component>

条件渲染和列表渲染 <template><block>

示例

1
2
3
4
5
6
7
8
9
10
<template>
<view>
<template v-if="test">
<view>test 为 true 时显示</view>
</template>
<template v-else>
<view>test 为 false 时显示</view>
</template>
</view>
</template>

过渡效果 <transition><transition-group>

示例

1
2
3
<transition name="fade">
<div v-show="show">这是一段会淡入淡出的文字。</div>
</transition>

缓存组件 <keep-alive>

内容分发 <slot>

示例

1
2
3
4
5
<my-component>
<template v-slot:default>
<p>默认插槽内容</p>
</template>
</my-component>

uniapp组件使用差异

组件命名规则

在 Vue 中注册组件时,需要为其指定一个名称。定义组件名的方式有两种:

Kebab-case(短横线分隔命名)
PascalCase(首字母大写命名)

组件目录结构

在 UniApp 工程中,自定义组件应存放在根目录下的 components 文件夹内,并遵循以下目录结构:

1
2
3
4
│─components
│ └─componentA
│ └─componentA.vue // 可复用的 componentA 组件
│ └─component-a.vue // 可复用的 component-a 组件

全局注册

  1. main.js 中引入并全局注册组件。
  2. 注册后,该组件可在所有页面中直接使用。
1
2
3
4
5
6
7
8
9
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 }
}
注意事项

局部注册

传统方法
  1. 在需要使用的页面通过 import 引入组件。
  2. components 选项中注册该组件。
1
2
3
4
5
6
7
8
9
10
11
12
13
<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 方式
1
2
3
4
5
6
7
8
9
<template>
<view>
<uni-badge text="1"></uni-badge>
</view>
</template>

<script>
export default {}
</script>

Easycom 特性

UniApp 插件市场

注意事项