uniapp学习代码
uniapp 学习代码指南
基础环境搭建
确保已安装 HBuilderX 开发工具,这是 uniapp 官方推荐的 IDE。下载地址可在官网找到。创建新项目时选择 uniapp 模板,支持 Vue.js 语法。
安装必要的依赖:
npm install -g @vue/cli
npm install -g @dcloudio/uni-app
项目结构解析
典型 uniapp 项目包含以下目录:
pages:存放页面文件,每个页面是一个文件夹static:存放静态资源如图片components:可复用组件App.vue:应用入口文件main.js:应用主逻辑文件manifest.json:应用配置信息pages.json:页面路由配置
基本页面开发
创建页面文件 pages/index/index.vue:
<template>
<view class="container">
<text>{{ message }}</text>
<button @click="changeText">点击修改</button>
</view>
</template>
<script>
export default {
data() {
return {
message: 'Hello uniapp'
}
},
methods: {
changeText() {
this.message = '文本已修改'
}
}
}
</script>
<style>
.container {
padding: 20px;
}
button {
margin-top: 10px;
}
</style>
路由配置
在 pages.json 中配置页面路由:
{
"pages": [
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "首页"
}
}
],
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
}
}
API 调用示例
调用设备 API 获取系统信息:
uni.getSystemInfo({
success: function(res) {
console.log(res.model); // 设备型号
console.log(res.platform); // 平台信息
}
});
跨平台适配
使用条件编译处理平台差异:

// #ifdef H5
console.log('这是H5平台');
// #endif
// #ifdef MP-WEIXIN
console.log('这是微信小程序平台');
// #endif
组件通信
父子组件通信示例: 父组件:
<template>
<child-component :msg="parentMsg" @childEvent="handleChildEvent"></child-component>
</template>
<script>
import ChildComponent from '@/components/ChildComponent.vue';
export default {
components: { ChildComponent },
data() {
return {
parentMsg: '父组件消息'
}
},
methods: {
handleChildEvent(payload) {
console.log('收到子组件消息:', payload);
}
}
}
</script>
子组件:
<template>
<view>
<text>{{ msg }}</text>
<button @click="sendToParent">通知父组件</button>
</view>
</template>
<script>
export default {
props: ['msg'],
methods: {
sendToParent() {
this.$emit('childEvent', '来自子组件的消息');
}
}
}
</script>
状态管理
使用 Vuex 进行状态管理:
创建 store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
export default store
在 main.js 中引入:

import store from './store'
const app = new Vue({
store,
...App
})
app.$mount()
组件中使用:
// 获取状态
this.$store.state.count
// 提交变更
this.$store.commit('increment')
网络请求
使用 uni.request 发送 HTTP 请求:
uni.request({
url: 'https://example.com/api',
method: 'GET',
data: {
key: 'value'
},
success: (res) => {
console.log(res.data);
},
fail: (err) => {
console.error(err);
}
});
打包发布
H5 打包:
npm run build:h5
小程序打包需在 HBuilderX 中选择对应平台的发行菜单。iOS 和 Android 原生应用打包需要配置证书和签名信息。
调试技巧
使用 Chrome 开发者工具调试 H5 版本。小程序版本可使用对应平台的开发者工具调试。真机调试需要连接设备并开启调试模式。





