uniapp 数据操作
uniapp 数据操作
数据绑定与渲染
在uniapp中,数据绑定使用双花括号{{}}语法,类似于Vue.js。在模板中直接绑定数据变量:
<template>
<view>{{ message }}</view>
</template>
<script>
export default {
data() {
return {
message: 'Hello uniapp'
}
}
}
</script>
数据更新与响应式
通过修改data中的属性实现数据更新,uniapp会自动触发视图更新:
export default {
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
}
}
}
列表渲染
使用v-for指令渲染数组数据,建议为每项添加唯一key:
<template>
<view v-for="(item, index) in list" :key="index">
{{ item.name }}
</view>
</template>
<script>
export default {
data() {
return {
list: [
{ name: 'Item 1' },
{ name: 'Item 2' }
]
}
}
}
</script>
条件渲染
使用v-if和v-show控制元素显示:
<view v-if="isVisible">显示内容</view>
<view v-show="isActive">动态显示</view>
表单数据绑定
通过v-model实现表单双向绑定:
<input v-model="inputValue" />
<checkbox-group @change="checkboxChange">
<checkbox value="1" />选项1
</checkbox-group>
数据存储
使用uni.setStorage和uni.getStorage进行本地数据存储:
// 异步存储
uni.setStorage({
key: 'key',
data: 'value',
success: function() {
console.log('存储成功')
}
})
// 同步存储
try {
uni.setStorageSync('key', 'value')
} catch (e) {
console.error(e)
}
网络请求
通过uni.request获取远程数据:
uni.request({
url: 'https://example.com/api',
method: 'GET',
success: (res) => {
this.dataList = res.data
},
fail: (err) => {
console.error(err)
}
})
全局数据管理
对于复杂应用,可使用Vuex进行状态管理:
- 创建store文件
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex)
const store = new Vuex.Store({ state: { token: '' }, mutations: { setToken(state, token) { state.token = token } } })
2. 在main.js中引入
```javascript
import store from './store'
const app = new Vue({
store,
...App
})
- 组件中使用
this.$store.commit('setToken', 'newToken') const token = this.$store.state.token
数据缓存策略
对于频繁访问但变化不大的数据,可结合本地缓存和网络请求:
async loadData() {
try {
// 先尝试从缓存读取
const cache = uni.getStorageSync('cachedData')
if (cache && !this.forceRefresh) {
this.data = cache
return
}
// 缓存不存在或强制刷新时请求网络
const res = await uni.request({ url: 'api_url' })
this.data = res.data
uni.setStorageSync('cachedData', res.data)
} catch (e) {
console.error('数据加载失败', e)
}
}






