Askar
Askar

Reputation: 5854

How to list items from firebase in VueJS 2?

Github https://github.com/tenzan/vue-fruits/tree/29d9d612c8801388f06a01541bf93ffdb7712f9f

App.vue:

<template>
<FruitList></FruitList>
</template>

<script>

import FruitList from './components/FruitList'

export default {
  name: 'App',
  components: {
      FruitList
  }
}
</script>

FruitList.vue:

<template>
<div v-for="fruit in fruits">{{ fruit.name }}</div>
</template>

<script>
export default {
  name: "FruitList"
};
</script>

Firebase side looks as follows:

enter image description here

Error:

Failed to compile.

./node_modules/vue-loader/lib/template-compiler?{"id":"data-v-0b422dd2","hasScoped":false,"optionsId":"0","buble":{"transforms":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./src/components/FruitList.vue
(Emitted value instead of an instance of Error) 
  Error compiling template:
  
  <div v-for="fruit in fruits">{{ fruit.name }}</div>
  
  - Cannot use v-for on stateful component root element because it renders multiple elements.

 @ ./src/components/FruitList.vue 6:0-326
 @ ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"/Users/askar/work/vue/vue-fruits/node_modules/.cache/cache-loader"}!./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue
 @ ./src/App.vue
 @ ./src/main.js
 @ multi (webpack)-dev-server/client/index.js (webpack)/hot/dev-server.js ./src/main.js

UPDATE 1

FruitList.vue has been updated to

<template>
<div>
  <div v-for="fruit in fruits">{{ fruit.name }}</div>
</div>
</template>

<script>
export default {
  name: "FruitList"
};
</script>

This time getting a warning:

[Vue warn]: Property or method "fruits" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

found in

---> <FruitList> at src/components/FruitList.vue
       <App> at src/App.vue
         <Root>

Upvotes: 0

Views: 1249

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83058

You have to make fruits reactive by declaring it in the component’s data option:

<script>
export default {
  name: "FruitList",

  data() {
    return {
      fruits: []
    }
  }
};
</script>

and populate fruits with a query from Firebase.

To query Firebase from a vue.js application is quite a lengthy process to describe in a SO answer... I will rather point you to a good tutorial: https://www.youtube.com/watch?v=FXY1UyQfSFw&list=PL55RiY5tL51qxUbODJG9cgrsVd7ZHbPrt. Start looking at video #13 (and more specially video# 17)


Update:

This is another tutorial, based on the vuefire library:

https://appdividend.com/2018/04/21/vue-firebase-crud-example/

See Step 10 for fetching data from the RTDB

Upvotes: 2

Related Questions