uniapp组件写法
Uniapp 组件的基本写法
Uniapp 的组件写法与 Vue 类似,支持单文件组件(.vue 文件)。一个基本的组件通常包含三个部分:<template>、<script> 和 <style>。
<template>
<view class="my-component">
<text>{{ message }}</text>
<button @click="handleClick">点击我</button>
</view>
</template>
<script>
export default {
data() {
return {
message: 'Hello Uniapp!'
}
},
methods: {
handleClick() {
console.log('按钮被点击了')
}
}
}
</script>
<style>
.my-component {
padding: 20px;
}
button {
margin-top: 10px;
}
</style>
组件注册与使用
在 Uniapp 中,组件分为全局注册和局部注册两种方式。
全局注册
在 main.js 中注册组件,使其在整个应用中可用:
import Vue from 'vue'
import MyComponent from './components/MyComponent.vue'
Vue.component('my-component', MyComponent)
局部注册 在需要使用组件的页面中引入:
import MyComponent from '../../components/MyComponent.vue'
export default {
components: {
MyComponent
}
}
组件间通信
Uniapp 组件间通信主要有以下几种方式:

Props 传递数据 父组件向子组件传递数据:
<!-- 父组件 -->
<child-component :msg="parentMessage"></child-component>
<!-- 子组件 ChildComponent.vue -->
<script>
export default {
props: {
msg: String
}
}
</script>
$emit 触发事件 子组件向父组件发送事件:
<!-- 子组件 -->
<button @click="$emit('custom-event', payload)">触发事件</button>
<!-- 父组件 -->
<child-component @custom-event="handleEvent"></child-component>
使用 Vuex 状态管理 对于复杂应用,建议使用 Vuex 进行状态管理:

// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
// 组件中使用
this.$store.commit('increment')
console.log(this.$store.state.count)
生命周期钩子
Uniapp 组件支持 Vue 的生命周期钩子,同时还扩展了一些应用特有的生命周期:
export default {
onLoad() {
// 页面加载时触发
},
onShow() {
// 页面显示时触发
},
mounted() {
// 组件挂载完成
},
beforeDestroy() {
// 组件销毁前
}
}
样式作用域
使用 scoped 属性可以限制样式只作用于当前组件:
<style scoped>
/* 这些样式只作用于当前组件 */
.my-class {
color: red;
}
</style>
组件插槽
Uniapp 支持 Vue 的插槽机制,用于内容分发:
<!-- 父组件 -->
<my-component>
<template v-slot:default>默认内容</template>
<template v-slot:footer>页脚内容</template>
</my-component>
<!-- 子组件 MyComponent.vue -->
<view>
<slot></slot>
<view class="footer">
<slot name="footer"></slot>
</view>
</view>
注意事项
- 组件名应使用 kebab-case(短横线分隔命名)
- 避免在组件中使用
id选择器,因为 Uniapp 会编译到不同平台 - 组件中的
v-for循环需要指定唯一的key - 在小程序平台,组件样式可能会受到更多限制






