firebase vue_Firebase Cloud Firestore入门:构建Vue联系人应用

firebase vue

Sometime back in October, Google announced the beta release of Firebase's Cloud Firestore which is a fully-managed NoSQL document database for both mobile and web app development. Firestore was designed to easily store and sync your app's data at global scale.

早在10月的某个时候, Google宣布了Firebase Cloud Firestore的Beta版,这是一个完全托管的NoSQL文档数据库,用于移动和Web应用程序开发。 Firestore旨在轻松地在全球范围内存储和同步您的应用程序数据。

Cloud Firestore includes features such as:

Cloud Firestore包括以下功能:

  • Documents and collections with powerful querying

    具有强大查询功能的文档和集合
  • iOS, Android, and Web SDKs with offline data access

    具有离线数据访问权限的iOS,Android和Web SDK
  • Real-time data synchronization

    实时数据同步
  • Automatic, multi-region data replication with strong consistency

    具有强一致性的自动多区域数据复制
  • Node, Python, Go, and Java server SDKs

    节点,Python,Go和Java服务器SDK

In this tutorial, I will demonstrate how to get started with Firebase Cloud Firestore and also highlight the differences between Cloud Firestore and the existing Firebase Realtime Database.

在本教程中,我将演示如何使用Firebase Cloud Firestore,并重点介绍Cloud Firestore与现有Firebase Realtime Database之间的区别。

We'll be building a Contact Management app, it's a basic CRUD app and Cloud Firestore acts as the backend database. You'll be able to see all contacts, add a new contact and view an individual contact. The Contact Management app will be built using Vue.js.

我们将构建一个Contact Management应用程序,它是一个基本的CRUD应用程序,Cloud Firestore充当后端数据库。 您将能够查看所有联系人,添加新联系人以及查看单个联系人。 联系人管理应用将使用Vue.js构建。

A screenshot of the contact management app can be seen below and you can check out a live demo here.

联系人管理应用程序的屏幕截图可以在下面看到,您可以在此处查看实时演示。

To get started with the app, we'll be using vue-cli to quickly scaffold a Vue.js app and even more specifically, the webpack template will be used.

要开始使用该应用程序,我们将使用vue-cli快速搭建Vue.js应用程序,更具体地说,将使用webpack模板。

Open a terminal window and run the following command to install the vue-cli tool:

打开终端窗口,运行以下命令以安装vue-cli工具:

npm install -g vue-cli

Let's now create the Vue.js app, Run the following command in a working directory:

现在创建Vue.js应用程序,在工作目录中运行以下命令:

vue init webpack firestore

This will go ahead and create a folder titled firestore containing a working Vue.js app with features like Hot Module Reloading, Webpack and vue-loader for single file components, and routes. Navigate to the firestore folder and run the npm run dev command to see the app live at http://localhost:8080.

这将继续创建名为文件夹firestore含有如H加时赛中号 odule [R eloading,的WebPack和特色工作Vue.js应用vue-loader单文件组件和路由。 导航到firestore文件夹并运行npm run dev命令以在http:// localhost:8080上查看该应用程序。

设置Cloud Firestore ( Setting up Cloud Firestore )

To begin using Firestore, you'll need a Gmail account, once that's good to go, you can sign in to https://console.firebase.google.com and create a new project.

要开始使用Firestore,您需要一个Gmail帐户,一旦登录成功,您可以登录https://console.firebase.google.com并创建一个新项目。

You should get a dashboard similar to the one below. This dashboard contains all of Firebase's other services that can be used in your application.

您应该获得一个类似于以下仪表盘的仪表盘。 此仪表板包含可在您的应用程序中使用的Firebase的所有其他服务。

Click on "Add Firebase to your web app" and copy the config details specific to your project to a safe location as you'll be needing it later.

单击“将Firebase添加到您的Web应用程序”,然后将特定于您项目的配置详细信息复制到安全位置,以备日后使用。

Under the Develop menu, click on the Database link and under the database tab, click “Try Firestore Beta” and “Start in Test Mode”. That should take you to a dashboard where you can view the database as it changes in real time.

在“开发”菜单下,单击“数据库”链接,然后在“数据库”选项卡下,单击“尝试Firestore Beta”和“以测试模式启动”。 这将带您进入仪表板,您可以在其中实时查看数据库更改。

With Firestore, we'll be dealing with documents and collections. Data is usually stored in documents, documents are stored in collections. A document may contain a collection and a collection may contain a document.

使用Firestore,我们将处理文档和集合。 数据通常存储在文档中,文档存储在集合中。 一个文档可能包含一个集合,而一个集合可能包含一个文档。

Vue.js和Firestore ( Vue.js and Firestore )

Let's get back to coding. Open the components folder and create two JavaScript files in it; firebaseConfig.js and firebaseInit.js. The firebaseConfig.js file will contain the config values gotten from the Firebase dashboard, we'll be exporting so it can be used in other locations.

让我们回到编码。 打开components文件夹并在其中创建两个JavaScript文件。 firebaseConfig.jsfirebaseInit.jsfirebaseConfig.js文件将包含从Firebase仪表板获取的配置值,我们将进行导出,以便可以在其他位置使用它。

export default {
  apiKey: 'AIzaSyDr0-Mef6D1RZsD2NoBaPOwordhUW58MyU',
  authDomain: 'contacts-app-dca62.firebaseapp.com',
  databaseURL: 'https://contacts-app-dca62.firebaseio.com',
  projectId: 'contacts-app-dca62',
  storageBucket: 'contacts-app-dca62.appspot.com',
  messagingSenderId: '715354469790'
}

We have a Firebase config file, but we need to initialize it somewhere, we can do that in the firebaseInit.js file like this:

我们有一个Firebase配置文件,但是我们需要在某个地方对其进行初始化,我们可以在firebaseInit.js文件中执行以下操作:

import firebase from 'firebase'
import 'firebase/firestore'
import firebaseConfig from './firebaseConfig'
const firebaseApp = firebase.initializeApp(firebaseConfig)
export default firebaseApp.firestore()

In the code block above, firebase and firestore were both imported, as well as the firebaseConfig.js file created earlier. The config file is used to initialize Firebase in the project and is also exported with the firestore function.

在上面的代码块中, firebasefirestore以及先前创建的firebaseConfig.js文件都已导入。 配置文件用于在项目中初始化Firebase,并且还与firestore函数一起导出。

Let's create the different components that will be used for the app. We'll be needing Home.vue, NewContact.vue and ViewContact.vue components. You can go ahead and create these files in the components folder.

让我们创建将用于该应用程序的不同组件。 我们将需要Home.vueNewContact.vueViewContact.vue组件。 您可以继续在components文件夹中创建这些文件。

Before we edit each component, let's update the router file to accommodate these new components. Navigate to the router folder, open up the index.js file in it and edit it with the code block below:

在编辑每个组件之前,让我们更新路由器文件以容纳这些新组件。 导航到router文件夹,在其中打开index.js文件,并使用以下代码块对其进行编辑:

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import ViewContact from '@/components/ViewContact'
import NewContact from '@/components/NewContact'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/add',
      name: 'new-contact',
      component: NewContact
    },
    {
      path: '/:person',
      name: 'view-contact',
      component: ViewContact
    }
  ]
})

In the code block above, we imported the components to be used for the different routes that will be used in the app. The Home component is responsible for serving the / route, the NewContact component is used to serve the /add route and the ViewContact component is used to serve the /:person route.

在上面的代码块中,我们导入了将用于应用程序中不同路线的组件。 Home组件负责服务/路由, NewContact组件用于服务/add路由, ViewContact组件用于服务/:person路由。

Now that the routes have been defined, we can begin editing the components. Let's start with the NewContact component. Open up the NewContact.vue file in the components folder. It's very common for .vue files to be divided into three sections; <template></template>, <script></script> and <style></style>. I'll highlight the code in each section before putting it all together at the end.

现在已经定义了路线,我们可以开始编辑组件。 让我们从NewContact组件开始。 打开components文件夹中的NewContact.vue文件。 .vue文件通常分为三个部分,这很常见。 <template></template><script></script><style></style> 。 在最后将它们放在一起之前,我将在每个部分中突出显示代码。

The <script></script> section contains the main JavaScript code and you can proceed to put in the following code block

<script></script>部分包含主要JavaScript代码,您可以继续放入以下代码块

<script>
    import db from './firebaseInit'
    export default {
      name: 'new-contact',
      data () {
        return {
          firstname: null,
          lastname: null,
          emailaddress: null,
          phonenumber: null
        }
      },
      methods: {
        saveContact () {
          db.collection('contacts').add({
            firstname: this.firstname,
            lastname: this.lastname,
            emailaddress: this.emailaddress,
            phonenumber: this.phonenumber,
            slug: this.generateUUID()
          })
            .then(function (docRef) {
              console.log('Document written with ID: ', docRef.id)
            })
            .catch(function (error) {
              console.error('Error adding document: ', error)
            })
        },
        generateUUID () {
          let d = new Date().getTime()
          let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            let r = (d + Math.random() * 16) % 16 | 0
            d = Math.floor(d / 16)
            return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
          })
          return uuid
        }
      }
    }
</script>

In the code block above, the firebaseInit.js file which was created earlier, is imported as db. In the methods object, there's the saveContact function which essentially saves the new contact to the Firestore DB. This line db.collection('contacts').add() is a way to add data to the Firestore DB, it's a way of saying add this data to the collection called contacts (or create one if it doesn't exist.). Cloud Firestore stores data in Documents, which are stored in Collections. Inside the .add() function, the contact details gotten from the form which will be created soon is being sent to Firestore along with a unique slug which is generated by the generateUUID function.

在上面的代码块中,先前创建的firebaseInit.js文件作为db导入。 在methods对象中,具有saveContact函数,该函数实际上将新联系人保存到Firestore DB。 db.collection('contacts').add()这一行是将数据添加到Firestore DB的一种方法,这是一种表示将这些数据添加到称为contacts的集合的方法(如果不存在则创建一个)。 。 Cloud Firestore将数据存储在文档中,该文档存储在集合中。 在.add()函数内部,将从即将创建的表单中获取的详细联系信息以及由generateUUID函数生成的唯一.add()发送到Firestore。

Next, we'll edit the <template></template> section and edit the HTML needed to create the form to add new contacts.

接下来,我们将编辑<template></template>部分,并编辑创建表单以添加新联系人所需HTML。

<template>

  <section class="container">
    <h1>Add New Contact</h1>

    <form @submit.prevent="saveContact">

      <div class="field">
        <label class="label">First Name</label>
        <div class="control">
          <input class="input" type="text" placeholder="First Name" v-model="firstname" required>
        </div>
      </div>

      <div class="field">
        <label class="label">Last Name</label>
        <div class="control">
          <input class="input" type="text" placeholder="Last Name" v-model="lastname" required>
        </div>
      </div>

      <div class="field">
        <label class="label">Email Address</label>
        <div class="control">
          <input class="input" type="email" placeholder="Email Address" v-model="emailaddress" required>
        </div>
      </div>

      <div class="field">
        <label class="label">Phone Number</label>
        <div class="control">
          <input class="input" type="text" placeholder="Phone Number" v-model="phonenumber" required>
        </div>
      </div>

      <div class="field">
        <div class="control">
          <button type="submit" class="button is-link">Submit</button>
        </div>
      </div>

    </form>
  </section>

</template>

In the code block above, we created the HTML form that adds a new contact to the Firestore DB. The value of each input tag is bound to the defined properties in the data() function via Vue.js' v-model.

在上面的代码块中,我们创建了HTML表单,该表单向Firestore DB添加了新联系人。 每个input标签的值通过Vue.js的v-model绑定到data()函数中定义的属性。

The styling for this form was done in the <style></style section and can be seen below.

此表单的样式已在<style></style部分中完成,可以在下面看到。

<style scoped>

  section {
    height: 100vh;
  }

  h1 {
    font-size: 30px;
    margin: 30px 0;
  }

  .input {
    height: 40px;
  }

</style>

Here's the NewContact.vue file in its whole entirety.

这是完整的NewContact.vue文件。

The next component we'll go through is the Home component. This component is used to serve the / route and it simply displays all the contacts in the Firestore DB and an optional button to view a contact individually.

我们将要经历的下一个组件是Home组件。 此组件用于提供/路由,它仅显示Firestore数据库中的所有联系人,并提供一个可选按钮来单独查看联系人。

Open up the Home.vue file and edit it with the content of the GitHub Gist below.

打开Home.vue文件,并使用下面的GitHub Gist的内容进行编辑。

Let's go through the code block above, the div with a class of loader-section and conditional rendering v-if=loading is essentially a placeholder and acts as a loading state until the required data is successfully fetched from Firestore.

让我们看一下上面的代码块,具有一类loader-section和条件渲染v-if=loadingdiv本质v-if=loading是一个占位符,并充当加载状态,直到从Firestore成功获取所需的数据为止。

The div with a class of user-list and directive v-for=person in contacts is the UI needed to populate all the contacts from the data gotten from Firestore. We'll see how to query data from Firestore next.

v-for=person in contacts带有一类user-list和指令v-for=person in contactsdiv是从Firestore获取的数据中填充所有通讯录所需的UI。 接下来,我们将介绍如何从Firestore查询数据。

In the <script></script> section of Home.vue, the first line of code is used to import the Firebase config just like we did in the NewContact component. In the created() function, the line db.collection('contacts').get() is used to get all data from the collection named contacts. The data is then pushed into the existing contacts array which was defined in the data() function.

Home.vue<script></script>部分中,第一行代码用于导入Firebase配置,就像在NewContact组件中所做的NewContact 。 在created()函数中, db.collection('contacts').get()用于从名为contacts的集合中获取所有数据。 然后,将数据推送到data()函数中定义的现有contacts数组中。

One other thing to note in the code block above is the button/link that leads to the page where you can view an individual contact.

在上面的代码块中要注意的另一件事是指向页面的按钮/链接,您可以在其中查看单个联系人。

<router-link class="button is-primary" v-bind:to="{ name: 'view-contact', params: { person: person.slug }}">View Person</router-link>

The v-bind:to directive is used to dynamically bind the person segment to the contact's slug. This basically means that you use the slug to access an individual contact page, so something like this: http://localhost:8080/#/7099198a-5ec5-48ae-b8de-2befb5352f78 where the random string of characters is the slug. This was established in the routes file above where we did something like this:

v-bind:to指令用于将person段动态绑定到联系人的子段。 基本上,这意味着您可以使用Slug来访问单个联系人页面,所以类似这样: http:// localhost:8080 /#/ 7099198a-5ec5-48ae-b8de-2befb5352f78 ,其中随机字符串是Slug 。 这是在上面的路由文件中建立的,我们在其中做了如下操作:

{
      path: '/:person',
      name: 'view-contact',
      component: ViewContact
    }

The next and last component to be edited is the ViewContact component. Open up the ViewContact.vue file and edit it with the content of the GitHub Gist below:

下一个也是最后一个要编辑的组件是ViewContact组件。 打开ViewContact.vue文件,并使用以下GitHub Gist的内容对其进行编辑:

Let's go through the code above. The <template></template> section contains the UI that's set to display the details of the contact. The various text interpolations in the template section are set to defined properties in the data() function in the <script></script> section.

让我们看一下上面的代码。 <template></template>部分包含用于显示联系人详细信息的UI。 模板部分中的各种文本插值在<script></script>部分的data()函数中设置为已定义的属性。

The beforeRouteEnter() function is a navigation guard. Navigation guards are used to guard navigations either by redirecting it or canceling it. Navigation Guards may be resolved asynchronously, and the navigation is considered pending before all hooks have been resolved. That means until the guard has been resolved, users won't be able to visit the route in which the navigation guard is. It can be used to check if a user is authenticated in an app or some data has finished loading.

beforeRouteEnter()函数是一个导航保护。 导航保护用于通过重定向或取消导航来保护导航。 导航卫士可以异步解决,并且在解决所有挂钩之前,导航被视为挂起。 这意味着在保护措施解决之前,用户将无法访问导航保护装置所在的路线。 它可用于检查用户是否在应用程序中通过了身份验证或某些数据已完成加载。

The beforeRouteEnter() function accepts three parameters, to, from, next.

beforeRouteEnter()函数接受三个参数tofromnext

  • to: the target Route Object being navigated to.

    to :要导航到的目标Route对象。

  • from: the current route being navigated away from.

    from :从当前导航离开的路线。

  • next(): this function must be called to resolve the hook.

    next() :必须调用此函数才能解决钩子。

In this case, we are using the navigation guard to ensure that the data from Firestore has been successfully retrieved. So how exactly are we getting the data for a particular document in Firestore?

在这种情况下,我们将使用导航防护来确保已成功检索到Firestore中的数据。 那么,我们究竟如何在Firestore中获取特定文档的数据?

We use the .where() function to query for the data required as seen below:

我们使用.where()函数查询所需的数据,如下所示:

db.collection('contacts').where('slug', '==', this.$route.params.person).get().then((querySnapshot) => {
      querySnapshot.forEach((doc) => {
        console.log(doc.id, ' => ', doc.data())
        this.firstname = doc.data().firstname
        this.lastname = doc.data().lastname
        this.emailaddress = doc.data().emailaddress
        this.phonenumber = doc.data().phonenumber
      })
})

The where() function takes in three parameters; an existing name of a field key in the Firestore DB (in this case, slug), the == sign, and the string in which to query the Firebase DB with (in this case, the $route.params.person string).

where()函数接受三个参数; Firestore数据库中字段键的现有名称(在本例中为Slug), ==符号以及用于查询Firebase DB的字符串(在本例中为$ route.params.person字符串)。

One more thing before running the app, we'll need to add the Bulma CSS framework to the project. You can do that by simply adding the line of code below to the index.html between the head tags.

在运行该应用程序之前,还有一件事,我们需要将Bulma CSS框架添加到项目中。 您可以通过简单地将以下代码行添加到head标签之间的index.html来实现。

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.min.css">

With that being done, you can run the app with the command npm run dev and you should the app live at http://localhost:8080

完成后,您可以使用命令npm run dev运行该应用程序,并且该应用程序应位于http:// localhost:8080

Cloud Firestore与实时数据库之间的异同 ( Differences and similarities between Cloud Firestore and Realtime Database )

Now that we have seen how easy it is to get started with Firestore, it's time to ask questions like:

既然我们已经了解了使用Firestore的难度,现在该提出以下问题了:

  • What's the difference between Cloud Firestore and Realtime Database?

    Cloud Firestore和实时数据库之间有什么区别?
  • How do I determine when to use Cloud Firestore or Realtime Database?

    如何确定何时使用Cloud Firestore或实时数据库?
  • Will Realtime Database be deprecated?

    实时数据库会被弃用吗?

There really is no difference between the two technologies, they both offer the same functionalities as seen here, the only advantage Cloud Firestore has, is in terms of scaling. Cloud Firestore was built in close collaboration with the Google Cloud Platform team and that means Cloud Firestore was built to scale right from the beginning.

两种技术之间确实没有区别,它们都提供了与此处所示相同的功能,Cloud Firestore的唯一优势在于扩展性。 Cloud Firestore是与Google Cloud Platform团队紧密合作构建的,这意味着Cloud Firestore的构建从一开始就可以扩展。

Also, the Realtime Database is basically a JSON tree where you can store anything with no real structure or organization, Cloud Firestore is actually structured. Cloud Firestore is a document-model database, which means that all of your data is stored in objects called documents that consist of key-value pairs — and these values can contain any number of things, from strings to floats to binary data to JSON-y looking objects the team likes to call maps. These documents, in turn, are grouped into collections.

此外,实时数据库基本上是一棵JSON树,您可以在其中存储没有实际结构或组织的任何内容,而Cloud Firestore实际上是结构化的。 Cloud Firestore是一个文档模型数据库,这意味着您的所有数据都存储在称为文档的对象中,该对象由键值对组成-这些值可以包含许多内容,从字符串到浮点数到二进制数据再到JSON-团队喜欢调用地图的对象。 这些文档又被归为集合。

The Realtime Database may be used in cases where you are trying to optimize for cost and latency, and you can even go ahead to use both databases together. This also means Realtime Database is not going anywhere, both databases co-exist. It's also important to note that Cloud Firestore is in beta and it would be good to keep abreast of new developments so as to know if there will be any breaking changes.

在您尝试优化成本和延迟的情况下,可以使用实时数据库,甚至可以一起使用这两个数据库。 这也意味着实时数据库不会无处可去,两个数据库并存。 还需要注意的是,Cloud Firestore处于beta版,因此最好及时了解新的开发动态,以便知道是否会有任何重大更改。

结论 ( Conclusion )

In this tutorial, we saw how easy it is to get started with the new Cloud Firestore by Google and also touched on some points when comparing it to the already existing Realtime Database.

在本教程中,我们看到了使用Google的新Cloud Firestore入门非常容易,并且在与现有的实时数据库进行比较时还谈到了一些要点。

The codebase for the app we built above can be seen here. Feel free to play with it and build stuff. The live demo also exists here.

我们上面构建的应用程序的代码库可以在这里看到。 随意使用它并构建东西。 现场演示也在这里

翻译自: https://scotch.io/tutorials/getting-started-with-firebase-cloud-firestore-build-a-vue-contact-app

firebase vue

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值