uniapp数据实战
uniapp数据实战:核心方法与技巧
数据绑定与响应式更新
uniapp基于Vue.js,数据绑定通过{{}}语法或v-model指令实现。响应式更新需注意:
- 对象新增属性需使用
this.$set,否则无法触发视图更新。 - 数组直接赋值需用新数组替换原数组,或调用
push、splice等Vue包裹的方法。
示例代码:
data() {
return {
list: [1, 2, 3],
user: { name: 'Alice' }
}
},
methods: {
updateData() {
this.$set(this.user, 'age', 20); // 响应式新增属性
this.list = [...this.list, 4]; // 替换数组触发更新
}
}
跨页面数据传递
- URL参数传递:通过
uni.navigateTo的url拼接参数,目标页通过onLoad的options接收。 - 全局变量:使用
uni.$emit和uni.$on实现事件总线通信。 - 本地存储:
uni.setStorageSync存储数据,uni.getStorageSync读取。
示例:
// 页面A传递参数
uni.navigateTo({
url: '/pages/detail?id=123'
});
// 页面B接收参数
onLoad(options) {
console.log(options.id); // 输出123
}
网络请求封装
推荐使用uni.request封装为Promise风格,便于异步处理:
export const http = (url, method = 'GET', data = {}) => {
return new Promise((resolve, reject) => {
uni.request({
url: 'https://api.example.com' + url,
method,
data,
success: (res) => resolve(res.data),
fail: (err) => reject(err)
});
});
};
// 调用示例
async fetchData() {
try {
const res = await http('/list', 'POST', { page: 1 });
console.log(res);
} catch (error) {
console.error(error);
}
}
数据缓存策略
- 短期缓存:使用
uni.setStorage存储接口返回数据,下次请求前优先读取缓存。 - 数据过期:通过时间戳判断缓存是否过期,例如设置10分钟有效期。
示例:
const KEY = 'cache_data';
function getCache() {
const cache = uni.getStorageSync(KEY);
if (cache && Date.now() - cache.time < 600000) {
return cache.data;
}
return null;
}
function setCache(data) {
uni.setStorageSync(KEY, { data, time: Date.now() });
}
性能优化建议
- 分页加载数据时,使用
scroll-view或onReachBottom事件实现懒加载。 - 大数据列表渲染时,使用
v-for的key属性,或通过uni.$emit分片渲染。 - 避免频繁
setData,合并多次操作为单次更新。
通过以上方法,可高效处理uniapp中的数据操作与性能问题。







