0

我正在从另一个视图导航到一个视图,并将 itemdId 作为参数值传递给 vue 路由器。

我希望能够使用该 itemId 调用 firebase,以便我可以过滤数据并在 UI 中使用过滤后的结果/数据。我正在使用vuefire.

发生的事情是 vue 在 created() 中的数据可用之前开始渲染,我看到错误是控制台说视图正在引用未定义的属性值。

有没有办法在数据可用后渲染视图?

我已经尝试过 usingbeforeMount以及 ascreatedbeforeCreate方法。

请参见下面的代码:

<h1>{{projects[0].project_name}}</h1> //it says type error. cannot read property project_name of undefined. Sometimes on refresh it works but most times it does not. 

脚本代码如下:

    let projectsRef = db.ref('projects');
    export default {
        name: 'ProjectDetailsOpenInvesting',
        props: {
          data: Object
    },
    firebase:{
      projects: projectsRef
    },
    data(){
      return {
        projects:[],
        .....

      }
    },
    created(){
      var that = this;
      console.log(this.$route.params.itemid) //this works
      this.projects = this.projects.filter(function(p){
        return p.project_id == that.$route.params.itemid //this works as well
      })
    }

Firebase 截图在这里

4

1 回答 1

0

正如您所提到的,一种方法是在导航之后获取,即在组件的created钩子中获取数据。

为此,vuefire您需要以编程方式将实时数据库绑定projectsRef Reference到 Vue 应用程序中的projects属性,如下所示:

created(){
  console.log(this.$route.params.itemid)
  const itemId = this.$route.params.itemid;
  this.$rtdbBind('projects', projectsRef.orderByKey().equalTo(itemId)).then(projects => {
     this.projects === projects;
  });
}

API 文档中所述:

$rtdbBind 返回一个 Promise,一旦数据被检索并同步到状态中,该 Promise 就会被解析。

注意需要安装rtdbPlugin插件:https ://vuefire.vuejs.org/api/vuefire.html#rtdbplugin


另请注意,我们不是project在前端过滤所需的项目(用filter(function(p){return p.project_id == that.$route.params.itemid}))),而是在后端过滤它,在数据库级别(projectsRef.orderByKey().equalTo(itemId))更有效,避免从后端到前端(并避免为此下载量付费,请参阅https://firebase.google.com/pricing?authuser=0)。

于 2019-10-23T08:45:42.410 回答