我正在使用Nuxt JS,Cordova和Cordova原生存储(本质上是localstorage(构建一个混合应用程序。
我正在将对象保存到本机存储,并在mounted()
的页面加载中检索它,但是,无论我尝试访问对象数据,我都会收到以下错误:
[Object Object]
我在每页加载的组件中的JS是:
import { mapState } from 'vuex';
export default {
mounted () {
document.addEventListener("deviceready", this.getNativeStorage(), false)
},
methods: {
getNativeStorage() {
window.NativeStorage.getItem("beacon_native_storage", (value) => {
var parseObj = JSON.parse(value)
alert(parseObj)
alert(parseObj.localStorage)
}, (error) => {
alert(`Error: ${error.code}-${error.exception}`)
});
},
refreshNativeStorage(currentState) {
window.NativeStorage.initWithSuiteName("beacon");
window.NativeStorage.setItem("beacon_native_storage", JSON.stringify(currentState), () => {
alert('Stored currentState')
}, (error) => {
alert(`Error: ${error.code}`)
});
}
},
computed: {
state () {
return this.$store.state
}
},
watch: {
state: {
handler: function (val, Oldval) {
setTimeout(function () {
this.refreshNativeStorage(this.state)
}.bind(this), 10)
},
deep: true
}
}
}
来自 Vuex 的对象看起来像:
export const state = () => ({
pageTitle: 'App name',
dataUrls: [],
intervalData: [],
settings: [],
experimentalFeatures: [],
customAlertSeen: false,
user: null,
account: null,
payloadOutput: null
})
每次getItem
运行时,alert(parseObj)
总是返回[Object Object] rather than for instance, the data. And if I try returning
parseObj.localStorage.pageTitlewhich is clearly defined in
store/localStorage.jsit returns
undefined'
我哪里出错了?
所以,发生的情况是,localStorage存储字符串,而不是对象。
将项目保存到 localStorage 时,首先将其转换为字符串,然后在检索时从字符串分析它。
localStorage.setItem('a', {b:'c',d:'e'})
localStorage.getItem('a') // "[object Object]" <- note the quotes!
localStorage.setItem('a', JSON.stringify({b:'c',d:'e'}))
JSON.parse(localStorage.getItem('a')) // {b: "c", d: "e"}