Javascript 将firebase数据存储在localstorage中,然后推送到vue数据()

Javascript 将firebase数据存储在localstorage中,然后推送到vue数据(),javascript,firebase,vue.js,google-cloud-firestore,local-storage,Javascript,Firebase,Vue.js,Google Cloud Firestore,Local Storage,我不确定我是否在正确的轨道上,但我正在尝试将一些firebase数据存储到我创建的()钩子上的localstorage中,然后将其推送到我的vue data()中,以便我可以在我的应用程序中渲染它。但是我的localstorage没有正确设置firebase中的数据,因此当我在render中引用它时,我的文章属性为空:( 我的文章[]中有一些示例文章,展示了来自firebase的数据结构 *当未从本地存储引用数据时,数据不会按原样正确呈现 也许有人能给我指出正确的方向,我认为问题在于我调用了lo

我不确定我是否在正确的轨道上,但我正在尝试将一些firebase数据存储到我创建的()钩子上的localstorage中,然后将其推送到我的vue data()中,以便我可以在我的应用程序中渲染它。但是我的localstorage没有正确设置firebase中的数据,因此当我在render中引用它时,我的文章属性为空:(

我的文章[]中有一些示例文章,展示了来自firebase的数据结构 *当未从本地存储引用数据时,数据不会按原样正确呈现

也许有人能给我指出正确的方向,我认为问题在于我调用了localstorage来设置数据

这是我的组件

<template> </template>

<script>
const fb = require('../../fireconfig.js')

export default {
  name: 'Home',
  data:function() {
    return{
       articles: [
         {
           title: 'modern web app security',
           body: 'some content here about web app security',
           image: 'dd',
           tags: ['cyber security','web apps', 'web development']
        },
         {
           title: 'intro to ArcGIS',
           body: 'an article to show users how to do GIS stuff',
           image: 'dwwd',
           tags: ['arcgis','node js','gps services']
        },
        {
           title: 'Vue.js injecting props',
           body: 'this is how to inject vue props into a component',
           image: 'dwwd',
           tags: ['vue','props','components','web development','web apps'] //remember to make tags from db into an array by splitting at ','
        }
      ],
      categories:['web development', 'arcgis','cyber security','partnerships'], //these don't come from the db
      search: '',
      tagList: [],
      pages: null,
      drawing: swiggle,
      mainlogo: slush,
      tags: tagsThumb,
      me: mepic,
    }
  },
  props: {
    post: Object
  },

  created(){

    var dataArray = []

    if(localStorage.getItem('data').length === 0){
      console.log('initial local store', localStorage.getItem('data'))

          let ref = fb.db.collection('articles')
          ref.get()
        .then(snapshot => {
          if (snapshot.empty) {
            console.log('No matching documents.');
            return;
          }  

          snapshot.forEach(doc => {  //this works for each doc
            console.log(doc.id, '=>', doc.data());

            let obj = {
              title: doc.data().title,
              body: doc.data().body,
              image: doc.data().image,
              tags: doc.data().tags.split(",")
            }
              dataArray.push(obj)
          })

        })
        .then((dataArray)=>{
          console.log('heres the data array to set in the local store',dataArray)
          localStorage.setItem('data', JSON.stringify(dataArray));
          console.log(localStorage)
        })
        .then(()=>{
              this.articles = JSON.parse(localStorage.getItem('data')) //push all data to this.articles
              console.log('checking value of this.articles',this.articles)
        })

        .catch(err => {
          console.log('Error getting documents', err);
        });

    }else{
        console.log('local store', localStorage)
      if(JSON.parse(localStorage.getItem('data').length !== undefined)){

        this.articles = JSON.parse(localStorage.getItem('data'))
        console.log('final articles',this.articles)
      }

    }
  },


  methods:{

    searchResultsByCat(val){
      let result = []
      for(let i = 0; i < this.articles.length; i++){
        for(let j = 0; j < this.articles[i].tags.length; j++){
            if (this.articles[i].tags[j].includes(val)){
                result.push(this.articles[i])
          }
        }
      }
       this.$router.push({name: 'Search', params: {data: result, search: val} })
    },

    gotoArticle(article){
      this.$router.push({name: 'Article', params: {data: article} })
    }

  }
}
</script>




const fb=require('../../fireconfig.js')
导出默认值{
姓名:'家',
数据:函数(){
返回{
文章:[
{
标题:“现代web应用程序安全”,
正文:“这里有一些关于web应用程序安全性的内容”,
图片:“dd”,
标签:[“网络安全”、“网络应用”、“网络开发”]
},
{
标题:“ArcGIS简介”,
正文:“一篇向用户展示如何使用GIS的文章”,
图像:“dwwd”,
标签:['arcgis','node js','gps services']
},
{
标题:“Vue.js注入道具”,
正文:'这是如何将vue道具注入组件',
图像:“dwwd”,
标记:['vue'、'props'、'components'、'web development'、'web apps']//请记住,通过在'、'处拆分,将db中的标记生成一个数组
}
],
类别:[“web开发”、“arcgis”、“网络安全”、“合作伙伴关系”],//这些不是来自数据库
搜索:“”,
标记列表:[],
页码:空,
图纸:swiggle,
主标志:slush,
标签:Tagstumb,
我:mepic,
}
},
道具:{
post:Object
},
创建(){
var dataArray=[]
if(localStorage.getItem('data')。长度==0){
console.log('initiallocalstore',localStorage.getItem('data'))
let ref=fb.db.collection('articles')
参考get()
。然后(快照=>{
if(snapshot.empty){
console.log('没有匹配的文档');
回来
}  
snapshot.forEach(doc=>{//这适用于每个doc
console.log(doc.id'=>',doc.data());
设obj={
标题:doc.data().title,
正文:doc.data().body,
image:doc.data().image,
标记:doc.data().tags.split(“,”)
}
dataArray.push(obj)
})
})
。然后((数据数组)=>{
console.log('这里是要在本地存储中设置的数据数组',dataArray)
setItem('data',JSON.stringify(dataArray));
console.log(本地存储)
})
.然后(()=>{
this.articles=JSON.parse(localStorage.getItem('data'))//将所有数据推送到this.articles
console.log('检查this.articles',this.articles的值)
})
.catch(错误=>{
console.log('获取文档时出错',err);
});
}否则{
console.log('localstore',localStorage)
if(JSON.parse(localStorage.getItem('data').length!==未定义)){
this.articles=JSON.parse(localStorage.getItem('data'))
console.log('final articles',this.articles)
}
}
},
方法:{
searchResultsByCat(val){
让结果=[]
for(设i=0;i
调用
ref.get()
似乎返回了一个,因此这是一个异步操作,不会在同一周期内完成


换句话说,当您设置值时,对
then
的回调没有运行。要解决问题,您还应该将相关行移到该回调中。

我认为这行
let init=JSON.parse(localStorage.getItem('data')| |'[])
应该是这样的
let init=localStorage.init!==undefined?JSON.parse(localStorage.init):[]
谢谢,在对then()中本地存储的位置进行了调整后,我能够设置数据并正确地读回:)