【问题标题】:Getting a firebase object's key after it has been passed down as a prop in Vue在 Vue 中作为道具传递后获取 Firebase 对象的密钥
【发布时间】:2017-09-01 00:24:08
【问题描述】:

我是 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>

(请查看 cmets)

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

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

【问题讨论】:

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


    【解决方案1】:

    我假设您来自父组件的“想法”对象包含键,因此看起来像这样:

    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,并随意使用它。希望这对你有用。

    【讨论】:

      【解决方案2】:

      我不使用 Firebase,但假设您的“想法”数组是 Firebase 对象(或引用)的数组,您可能只需要在方法中使用 this.thought.key。

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

      【讨论】:

      • 密钥没有传递给子组件。请参阅更新后的问题以获取 thought 对象作为道具的屏幕截图。
      猜你喜欢
      • 2018-02-12
      • 1970-01-01
      • 2022-01-26
      • 2016-08-11
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      相关资源
      最近更新 更多