uniapp学习【vue3在uniapp中语法,使用element】
均基于
setup
语法糖
1.Vue3 核心语法
1.1 响应式数据(核心!页面交互的基础)
Vue3 通过ref
和reactive
实现响应式(数据变化时,页面自动更新)
方法 | 适用类型 | 访问 / 修改方式 | 示例 |
---|---|---|---|
ref | 基本类型(Number、String、Boolean) | 访问:变量名.value;修改:变量名.value = 新值 | const count = ref(0); count.value = 1 |
reactive | 对象 / 数组 | 直接访问 / 修改(无需.value) | const user = reactive({name: '张三'}); user.name = '李四' |
<script setup>
import { ref, reactive } from 'vue'// 1. ref示例(基本类型)
const username = ref('小白')
const age = ref(18)
const isShow = ref(false)// 修改ref数据
const changeName = () => {username.value = 'Uniapp开发者' // 必须用.value
}// 2. reactive示例(对象)
const user = reactive({name: '张三',address: {city: '北京'}
})// 修改reactive数据
const changeCity = () => {user.address.city = '上海' // 直接修改,无需.value
}// 3. reactive示例(数组)
const list = reactive([{ id: 1, text: '学习Uniapp' },{ id: 2, text: '学习Vue3' }
])// 向数组添加元素
const addItem = () => {list.push({ id: list.length + 1, text: '学习Element Plus' })
}
</script>
1.2生命周期钩子(控制页面 / 组件的执行时机)
Uniapp 支持两种生命周期:Vue3 生命周期和Uniapp 页面生命周期。开发小程序时,优先使用 Uniapp 页面生命周期(更贴合小程序场景)。
1.2.1 Uniapp 页面生命周期(常用)
钩子函数 | 触发时机 | 常用场景 |
---|---|---|
onLoad | 页面加载时触发(只触发一次) | 初始化数据、接收路由参数 |
onShow | 页面显示时触发(每次切换到前台都触发) | 刷新页面数据(如从详情页返回首页) |
onReady | 页面初次渲染完成时触发(只触发一次) | 操作 DOM、初始化第三方组件 |
onHide | 页面隐藏时触发(如切到其他 tab、退到后台) | 保存页面状态 |
onUnload | 页面卸载时触发(如关闭页面) | 清理定时器、取消网络请求 |
1.2.2 Vue3 生命周期
常用onMounted
(组件渲染完成)、onUnmounted
(组件卸载)
<script setup>
import { onMounted, onUnmounted } from 'vue'// 组件渲染完成时触发
onMounted(() => {console.log('自定义组件渲染完成')
})// 组件卸载时触发
onUnmounted(() => {console.log('自定义组件卸载')
})
</script>
1.3 事件处理(页面交互的核心)
1.3.1 绑定事件(@事件名
)
@click
(点击事件)、@input
(输入事件)、@change
(选择事件)
<template><view><!-- 点击事件 --><button @click="handleClick">点击</button><!-- 输入事件(实时获取输入内容) --><input @input="handleInput" placeholder="请输入内容" /><!-- 选择事件(如下拉选择) --><picker @change="handlePickerChange" range="{{['北京','上海','广州']}}"><view>选择城市:{{ selectedCity }}</view></picker></view>
</template><script setup>
import { ref } from 'vue'const selectedCity = ref('北京')// 点击事件处理
const handleClick = () => {uni.showToast({ title: '点击成功' })
}// 输入事件处理(e.detail.value是输入框的值)
const handleInput = (e) => {console.log('输入内容:', e.detail.value)
}// 选择事件处理(e.detail.value是选中的索引)
const handlePickerChange = (e) => {const cities = ['北京','上海','广州']selectedCity.value = cities[e.detail.value]
}
</script>
1.3.2 事件传参(@click="handleClick(参数)"
)
<template><view><!-- 传固定参数 --><button @click="handleSend('hello')">发送hello</button><!-- 传响应式数据 --><button @click="handleSend(username.value)">发送用户名</button><!-- 传事件对象+参数(需用$event) --><input @input="handleInputWithParam($event, 'input1')" placeholder="输入框1" /></view>
</template><script setup>
import { ref } from 'vue'const username = ref('小白')const handleSend = (msg) => {console.log('发送的消息:', msg)
}const handleInputWithParam = (e, inputId) => {console.log(`输入框${inputId}的值:`, e.detail.value)
}
</script>
1.4 模板语法(渲染页面 UI)
1.4.1 文本渲染({{ 变量名 }}
)
<template><view><text>用户名:{{ username }}</text><text>年龄:{{ age + 1 }}</text> <!-- 支持简单运算 --><text>是否成年:{{ age >= 18 ? '是' : '否' }}</text> <!-- 支持三元表达式 --></view>
</template><script setup>
import { ref } from 'vue'
const username = ref('小白')
const age = ref(18)
</script>
1.4.2 条件渲染(v-if
/v-else-if
/v-else
)
根据条件显示 / 隐藏元素(
v-if
会销毁 / 创建元素,v-show
只是隐藏 / 显示,频繁切换用v-show
)
<template><view><!-- v-if条件渲染 --><text v-if="isShow">显示这段文字</text><text v-else>隐藏时显示这段文字</text><!-- v-show条件渲染 --><text v-show="isShow">用v-show显示</text><button @click="toggleShow">切换显示/隐藏</button></view>
</template><script setup>
import { ref } from 'vue'
const isShow = ref(true)const toggleShow = () => {isShow.value = !isShow.value
}
</script>
1.4.3 列表渲染(v-for
)
循环渲染数组或对象,必须加
key
(唯一标识,提高性能)
<template><view><!-- 循环数组 --><view v-for="(item, index) in list" :key="item.id"><text>索引:{{ index }},内容:{{ item.text }}</text></view><!-- 循环对象 --><view v-for="(value, key) in user" :key="key"><text>{{ key }}:{{ value }}</text></view></view>
</template><script setup>
import { reactive } from 'vue'// 循环数组
const list = reactive([{ id: 1, text: '学习Uniapp' },{ id: 2, text: '学习Vue3' }
])// 循环对象
const user = reactive({name: '张三',age: 18
})
</script>
1.4.4 样式绑定(:class
/:style
)
<template><view><!-- :class绑定(对象形式) --><view :class="{ active: isActive, red: isRed }">动态class</view><!-- :class绑定(数组形式) --><view :class="[activeClass, redClass]">动态class数组</view><!-- :style绑定(对象形式) --><view :style="{ fontSize: fontSize + 'rpx', color: textColor }">动态style</view><button @click="toggleStyle">切换样式</button></view>
</template><script setup>
import { ref } from 'vue'// :class相关
const isActive = ref(true)
const isRed = ref(false)
const activeClass = ref('active')
const redClass = ref('red')// :style相关
const fontSize = ref(32)
const textColor = ref('#333')const toggleStyle = () => {isActive.value = !isActive.valueisRed.value = !isRed.valuefontSize.value = 40textColor.value = '#007aff'
}
</script><style>
.active {border: 2rpx solid #007aff;
}
.red {color: red;
}
</style>
2. Element Plus 引入与使用
Element Plus 是 Vue3 的 UI 组件库,需适配 Uniapp(部分组件需调整样式)
2.1 安装 Element Plus
打开 HBuilderX 的 “终端”(底部工具栏),输入以下命令(确保项目根目录正确)
npm install element-plus --save
等待安装完成(终端显示 “added xxx packages” 即成功)
2.2 全局引入 Element Plus
在main.js
中全局引入 Element Plus 和样式,无需在每个页面单独引入
// main.js
import { createSSRApp } from "vue";
import App from "./App.vue";// 1. 引入Element Plus
import ElementPlus from 'element-plus'
// 2. 引入Element Plus样式(必须引入,否则组件无样式)
import 'element-plus/dist/index.css'export function createApp() {const app = createSSRApp(App);// 3. 注册Element Plus到Vue实例app.use(ElementPlus);return {app,};
}
2.3 常用组件示例(适配小程序)
Element Plus 的大部分组件可在 Uniapp 中使用,以下是常用组件的示例(注意:部分组件如ElMenu
(导航菜单)在小程序中可能需要调整样式)
2.3.1 按钮
<template><view class="btn-container"><el-button type="primary">主要按钮</el-button><el-button type="success">成功按钮</el-button><el-button type="warning">警告按钮</el-button><el-button type="danger">危险按钮</el-button><el-button @click="handleBtnClick">点击事件按钮</el-button></view>
</template><script setup>
const handleBtnClick = () => {uni.showToast({ title: 'Element Plus按钮点击成功' })
}
</script><style scoped>
.btn-container {display: flex;gap: 20rpx;flex-wrap: wrap;padding: 20rpx;
}
</style>
2.3.2 输入框
<template><view class="input-container" style="padding: 20rpx;"><el-input v-model="inputValue" placeholder="请输入内容" @change="handleInputChange"/><text style="display: block; margin-top: 20rpx;">输入内容:{{ inputValue }}</text></view>
</template><script setup>
import { ref } from 'vue'
const inputValue = ref('')const handleInputChange = (value) => {console.log('输入框内容变化:', value)
}
</script>
2.3.3 弹窗
<template><view style="padding: 20rpx;"><el-button @click="dialogVisible = true">打开弹窗</el-button><el-dialog v-model="dialogVisible" title="Element Plus弹窗"width="80%" <!-- 小程序中建议用百分比控制宽度 -->><div>这是一个Element Plus的弹窗组件</div><template #footer><el-button @click="dialogVisible = false">取消</el-button><el-button type="primary" @click="dialogVisible = false">确定</el-button></template></el-dialog></view>
</template><script setup>
import { ref } from 'vue'
const dialogVisible = ref(false)
</script>
2.3.4 列表
<template><view style="padding: 20rpx;"><el-table :data="tableData" border style="width: 100%;"><el-table-column label="ID" prop="id" align="center" /><el-table-column label="名称" prop="name" align="center" /><el-table-column label="操作" align="center"><template #default="scope"><el-button size="small" @click="handleEdit(scope.row)">编辑</el-button></template></el-table-column></el-table></view>
</template><script setup>
import { reactive } from 'vue'// 表格数据
const tableData = reactive([{ id: 1, name: 'Uniapp' },{ id: 2, name: 'Vue3' },{ id: 3, name: 'Element Plus' }
])// 编辑事件(scope.row是当前行数据)
const handleEdit = (row) => {uni.showToast({ title: `编辑:${row.name}` })
}
</script>
2.4 小程序适配注意事项
样式冲突:Element Plus 默认样式可能与 Uniapp 冲突,可在样式中用
::v-deep
穿透scoped
修改组件样式:css
<style scoped> /* 修改ElButton的样式 */ ::v-deep .el-button--primary {background-color: #007aff !important; /* 小程序主题色 */ } </style>
组件尺寸:Element Plus 组件默认尺寸较大,可通过
size
属性(如size="small"
)或自定义样式缩小尺寸,适配小程序屏幕。不支持的组件:部分 Element Plus 组件(如
ElCarousel
(轮播)、ElUpload
(上传))在小程序中可能存在兼容性问题,建议优先使用 Uniapp 自带的swiper
(轮播)、uni.chooseImage
(图片选择)等 API。