获取firebase对象的密钥后,将其作为Vue中的prop传递

时间:2017-09-01 00:24:08

标签: firebase firebase-realtime-database vue.js vuejs2

我是Firebase的新手。我在firebase数据库中有一个thought模式,如下所示:

{
  title: "I should learn VueJS + Firebase",
  body: "With VueJS+Firebase, I can take over the worlddd! Here's how I'll do it..."
}

使用ListOfThoughts.vue组件,我们可以将thoughts呈现给我们的模板,如下所示:

<template>
  <div class="list-of-thoughts">
      <ThoughtItem v-for="thought in thoughts" :thought="thought" />
  </div>
</template>

<script>
import firebase from './../firebase'
import ThoughtItem from './ThoughtItem.vue'
export default {
  components: {
    ThoughtItem
  },
  data () {
    return {
      thoughts: []
    }
  },
  created() {
    const thoughtsRef = firebase.database().ref().child('thoughts');
    thoughtsRef.on('value', snapshot => {
      this.thoughts = snapshot.val();
    }, errorObject => {
      console.log('Error retrieving thoughts: ' + errorObject.code);
    })

  }
}
</script>

请注意,我们使用的ThoughtItem组件如下所示:

<template>
  <div class="thought">
    <h1>{{thought.title}}</h1>
    <p>{{thought.body}}</p>
  </div>
</template>

<script>
import firebase from './firebase'
export default {
  props: ['thought'],
  methods: {
    getThoughtKey() {
      // How can we access the Key of this particular `thought` here?
      // I need the key value to access the database object. Like this:
     firebase.database().ref().child(key);
    }
  }
}
</script>

(请查看评论)

我希望访问此thought对象的密钥,以便我可以更新它。传递给ThoughtItem组件的对象不包含密钥。如果我们将作为prop传递的thought对象记录到ThoughtItem组件,它看起来像这样:

Notice that there is no key property here

为了对这个thought对象运行进一步的CRUD操作,我们需要它的密钥。我们如何从这个子组件访问它的密钥?

2 个答案:

答案 0 :(得分:0)

我没有使用Firebase,但假设你的想法&#34; array是一个Firebase对象(或引用)的数组,您可能只需要在方法中使用this.thought.key。

getThoughtKey() {
 firebase.database().ref().child(this.thought.key);
}

答案 1 :(得分:0)

我假设父组件中的'思想'对象包含键,所以看起来像这样:

thoughts: {
    key1: {
        title: title1,
        body: body1
    },
    key2: {
        title: title2,
        body: body2
    }
}

至少,这是我在测试时设置this.thoughts = snap.val()的方式。

在Vue中迭代对象时,您可以访问正在迭代的项的键,如下所示:v-for="(thing,k) in myObject。现在,您可以在项目的任何位置使用k来获取密钥。在你的情况下,我会尝试

<ThoughtItem v-for="(thought,thoughtKey) in thoughts" :thought="thought" :thoughtKey="thoughtKey" />

然后,您可以接受thoughtKey作为子组件中的prop,并根据需要使用它。希望这对你有用。