Firebase Authentication in Vue.js 2 with VueFire

Firebase Authentication in Vue.js 2 with VueFire

Firebase provides a very simple way to setup authentication in your apps. Here we’ll explore how to setup a simple authentication workflow for VueJS 2+ apps using the Vuefire library.

Vuefire makes life even simpler by giving direct umschlüsselung and updates to firebase objects through Vue’s reactivity system.

Installing and Setting Up

Install firebase and Vuefire in your Vue.js project, through NPM or Yarn.


# NPM
$ npm install firebase vuefire -s

# Yarn
$ yarn add firebase vuefire

Then, in your app’s main file, enable the VueFire plugin.

File main.js

import './firebase';

import Vue from 'vue';
import App from 'App.vue';
import VueFire from 'vuefire';
Vue.use(VueFire);
new Vue({
  el: '#app',
  render: h => h(App)
});

Initiate the firebase connection

Now we need to initialize the firebase connection, for this purpose will create a filefirebase.js and initiate the firebase connection in it.


File firebase.js

import Firebase from 'firebase'

const firebaseApp = Firebase.initializeApp({
    // Your firebase configuration data here....

});
// Export the database for components to use.
export const db = firebaseApp.database();

Now, we can access data in our Firebase database directly from Vue components.

File app.vue

<template>
  <p v-for="book of books">
    {{book.name}}
  </p>
</template>
<script>
import {db} from './firebase';
export default {
  data() {
    return {
      books: {}
    }
  },
firebase: {
    books: {
      source: db.ref('books'),
      // error handeling.
      cancelCallback(err) {
        console.error(err);
      }
    }
  }
}
</script>

Whenever the book's collection updates, the book’s data object will update on the client as well. How’s that for a seamless reactive database?

Modifying data

You can modify arrays as normal in this.$firebaseRefs. (ie. this.$firebaseRefs.books.push({name: 'Tom Bombadil'})).


Normal Vue reactivity rules and caveats apply.

Unfortunately, modifying objects can be a bit trickier. That has to be done fairly manually using the firebase ref directly.

updateBookName(book, newName) {    this.$firebaseRefs.books.child(book['.key']).child('name').set(newName);
}

// Function to remove a book
removeBook(book) {
  this.$firebaseRefs.books.child(book['.key']).remove()
}

Important Links

Vuefire site

Firebase docs.

#HappyCoding & Keep ??!

Mr Malik

Founder & CEO At Sufix Tech. 250+ Businesses across USA rely on us for CRM Management , Building Funnels & Automations, Web Development, SEO, Media Buying, Video Editing , Graphic Designing. We are 100% White Label.

7 个月

Muhammad, thanks for sharing!

回复

要查看或添加评论,请登录

Muhammad Ayoub的更多文章

社区洞察

其他会员也浏览了