VueJs-#13 Vue Cloud FireStore

Pendahuluan

Pada tutorial sebelumnya kita membuat Vue Login menggunakan FirebaseUI, sekarang kita akan membuat ToDoList Page dan menyimpannya ke dalam FireStore.

Kita akan menggunakan proyek tutorial sebelumnya dan menambahkan ToDoList Page.

Persiapan

  1. Buat Proyek Vue Login menggunakan FirebaseUI

Membuat Page ToDoList

Siapkan Route, edit router.js, tambahkan baris berikut :

import Vue from "vue";
import Router from "vue-router";
import Home from "./views/Home.vue";
import Login from "./components/Login.vue";
import Profile from "./components/Profile.vue";
import Todos from '@/components/Todos'

import firebase from 'firebase/app';
import 'firebase/auth';

Vue.use(Router);

let router =  new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
        path: "/home",
        name: "Home",
        component: Home,
        meta: {
            auth: true
        }
    },
    {
        path: '/about',
        name: 'about',
        component: () => import('./views/About.vue'),
        meta: {
            auth: true
        }
    },
    {
        path: "/",
        name: "Login",
        component: Login,
        meta: {
            guest: true
        }
    },
    {
        path: "/profile",
        name: "Profile",
        component: Profile,
        meta: {
            auth: true
        }
    },
    {
        path: '/todo',
        name: 'Todos',
        component: Todos,
        meta: {
            auth: true
        }
    }
  ]
});
router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.auth)) {
      firebase.auth().onAuthStateChanged(user => {
        if (user) {
          next()
        } else {
          next({
            path: "/",
          })
        }
      })
    } else if (to.matched.some(record => record.meta.guest)) {
      firebase.auth().onAuthStateChanged(user => {
        if (user) {
          next({
            path: "/profile",
          })
        } else {
          next()
        }
      })
    } else {
      next()
    }
  })
  export default router

Buat Component, components/Todos.vue

<template>
    <div>
        <b-card no-body style="max-width: 20rem;margin:auto;" class="mt-5 text-center">
            <template v-slot:header>
                <h4 class="mb-0">To-Dos</h4>
            </template>
            <b-card-body>
                 <b-input-group prepend="To Do" class="mt-3">
                    <b-form-input id="new_todo" type="text" class="validate" v-model="todo.title"></b-form-input>
                    <b-input-group-append>
                        <b-button variant="outline-success" @click="addTodo">Add</b-button>
                    </b-input-group-append>
                </b-input-group>
            </b-card-body>
            <b-list-group flush>
                <b-list-group-item class="d-flex justify-content-between align-items-center"
                    v-for="todo in todos"
                    :key="todo.id"
                    :class="{ fade: todo.isCompleted }"
                >
                    <b-button variant="danger" size="sm" class="deleteIcon" @click="deleteToDo(todo.id)">X</b-button>
                    {{todo.title}}
                    <b-form-checkbox
                        type="checkbox"
                        :checked="todo.isCompleted"
                        @change="updateTodoItem(todo.id, $event)"
                        switch
                    >
                    </b-form-checkbox>
                </b-list-group-item>
            </b-list-group>
        </b-card>
    </div>
</template>
<script>
import firebase from 'firebase/app';
import 'firebase/firestore';
export default {
    data() {
        return {
            todos: [],
            todo: {
                title: ""
            }
        };
    },
    created() {
        this.getTodos();
    },
    methods: {
        addTodo() {
            firebase
                .firestore()
                .collection("users")
                .doc(firebase.auth().currentUser.uid)
                .collection("todos")
                .add({
                    title: this.todo.title,
                    createdAt: new Date(),
                    isCompleted: false
                });
        },
        async getTodos() {
            var todosRef = await firebase
                .firestore()
                .collection("users")
                .doc(firebase.auth().currentUser.uid)
                .collection("todos");
            todosRef.onSnapshot(snap => {
                this.todos = [];
                snap.forEach(doc => {
                    var todo = doc.data();
                    todo.id = doc.id;
                    this.todos.push(todo);
                });
            });
        },
        updateTodoItem(docId, e) {
            var isChecked = e;
            firebase
                .firestore()
                .collection("users")
                .doc(firebase.auth().currentUser.uid)
                .collection("todos")
                .doc(docId)
                .update({
                    isCompleted: isChecked
                });
        },
        deleteToDo(docId) {
            firebase
                .firestore()
                .collection("users")
                .doc(firebase.auth().currentUser.uid)
                .collection("todos")
                .doc(docId)
                .delete();
        }
    }
};
</script>
<style>
.fade {
    opacity: 0.4 !important;Jala
}
.collection.with-header {
    max-width: 500px;
    margin: 0 auto;
}
.deleteIcon {
    margin-right: 10px;
    cursor: pointer;
}
.deleteIcon:hover {
    opacity: 0.5;
}
</style>

Jalankan program, masuk menu “ToDo” :

ToDos
Struktur Cloud Firestore