全局数据
有时在接口请求的某个数据需要在多个页面使用,此时有2个方法
- [1] 将数据存储在本地—> 等价于浏览器的localStorage
- [2] 将数据存储在数据缓存中 -> 等价于vue中的vuex
[1]本地数据存储
- 官方文档:官方文档
<template>
<div class="wrapper">
<text id='text' @click='setValue'>存储数据</text>
<text id='text' @click='getValue'>获取数据</text>
</div>
</template>
<script>
import storage from '@system.storage'
import prompt from '@system.prompt'
export default {
setValue(){
storage.set({
key: 'test',
value: '11111',
success: function(data) {
prompt.showToast({
message: '存储成功'
})
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`)
}
})
},
getValue(){
storage.get({
key: 'test',
success: function(data) {
prompt.showToast({
message: data
})
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`)
}
})
}
}
</script>
[2] 数据缓存
将大部分页面都需要使用的数据存储在app.ux中,比如存储数据dataCache
data:{
dataCache:{}
}
// (引用类型)一定要在onCreate初始化,在data中设置的默认值不起作用(默认undefiend)
onCreate(){
this.dataCache = {}
},
使用app.ux中声明方法去获取、修改、删除
//获取 app 缓存的数据
getAppCache (key) {
return this.dataCache ? (this.dataCache[key] || '') : ''
},
// 设置 app 缓存的数据
setAppCache (key, val) {
if (val === '' && this.dataCache[key]) {
delete this.dataCache[key]
return
}
this.dataCache[key] = val
},
clearAppCache () {
this.dataCache = {}
}
在app.ux中声明的方法默认会被添加在
$app
身上,可以通过this.$app.方法名或者this. $app._def.方法名去获取
this.$app.setAppCache('type', 1111)
this.$app.getAppCache('type') // 1111
问题
// app.ux
data:{
dataCache:{
type: 0
}
}
//获取 app 缓存的数据
getAppCache (key) {
console.log(111111, this.dataCache) // 111111 undefiend
return this.dataCache ? (this.dataCache[key] || '') : ''
},
// 设置 app 缓存的数据
setAppCache (key, val) {
if (val === '' && this.dataCache[key]) {
delete this.dataCache[key]
return
}
this.dataCache[key] = val
},
clearAppCache () {
this.dataCache = {}
}
// 其他页面
console.log(this.$app.getAppCache('type')) // ‘’
疑问🤔️: 在data中定义的初始值不起作用?!!!
在onCreate生命周期中再将数据初始化一边
onCreate(){
this.dataCache = {}
},
此时再次调用this.$app.getAppCache(‘type’),此时可以正常获取了。
总结: 在data中数据的初始化不起作用,默认都是undefined
!!!
全局方法
在项目中封装的一些工具型方法,可以将其添加在全局对象global中,这样就可以在页面中直接使用(不需每次使用之前先引入)。
global对象
在快应用中不能使用BOM、DOM,因此也不能使用window作为全局对象。
在快应用中可以使用global
访问全局对象
在快应用中global对象可以直接使用,我们可以将封装的公共方法添加在global对象上(类似于将封装的公共方法添加在vue实例化对象上)。
- utils文件
// 公共方法文件 export default {...}
- 在app.ux中声明
<script> const utils = require('./helper/utils').default /* @desc: 注入方法至全局 global,以便页面调用 */ const hook2global = global.__proto__ || global hook2global.$utils = utils </script>
- 在其他页面中使用
$utils.getxxx()
$app
您可以在app.ux的< script >中引入一些公共的脚本,并暴露在当前 app 的对象上,然后就可以在页面 ux 文件的 ViewModel 中,通过this.$app.$def.xxx
访问,如下
// 公共方法文件
export default {...}
//app.ux文件
<script>
//import utils from './helper/utils'
const utils = require('./helper/utils').default
export default{
utils
}
</script>
// 其他ux页面
this.$app.$def.utils // 可以获取到处的公共对象
另外一些公用方法也可以直接声明在app.ux中
,这些方法也可以通过this.$app.$def.方法名
去使用, 也可以通过 this. $app.方法名
直接使用!
常量数据
在实际开发过程中,若是存在一些常量且在项目的多个地方使用时,可以将该数据存储在manifest.json
配置项的config.data
中。
在使用时可以通过$app.$data
去获取。