我正在使用Nuxt JS、Cordova和Cordova Native Storage (本质上是本地存储)构建一个混合应用程序。
我正在将一个对象保存到本机存储中,并在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`
我在哪里做错了?
发布于 2019-09-24 23:40:05
所以,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"}
https://stackoverflow.com/questions/58083732
复制相似问题