简体   繁体   English

在 Vue 中使用云 Firestore 更新 boolean 值

[英]Updating boolean value with cloud firestore in Vue

I'm new to both Vue and Firebase. So I'm trying to implement a very simple library app with both.我是 Vue 和 Firebase 的新手。所以我正在尝试用两者实现一个非常简单的库应用程序。 Here you can create a book object with title, author and whether it's been 'read' or not(Always false by default).在这里,您可以创建一本书 object,其中包含标题、作者以及是否已“阅读”(默认情况下始终为 false)。 Each component has a checkbox to update the value of the 'read' attribute.每个组件都有一个复选框来更新“读取”属性的值。 However, the updating function only updates the value once, and I'm expecting it to change every time the checkbox changes.但是,更新 function 只更新一次值,我希望每次复选框更改时它都会更改。 What am I doing wrong?我究竟做错了什么?

This is the template and the function in App.vue:这是 App.vue 中的模板和 function:

<template>
  <div id="app">
    <Header />
    <AddBook v-on:add-book="addBook" />
    <Books v-bind:books="books" v-on:del-book="deleteBook" v-on:update-book="updateBook" />
  </div>
</template>
updateBook(id, book) {
  console.log(book);
  db.collection("books")
    .doc(id)
    .update({
      read: !book.read,
    })
    .then(() => {
      console.log("Book successfully updated!");
    })
    .catch((error) => {
      console.error("Error updating book: ", error);
    });
}

And I'm passing the data with $emit from Book.vue:我正在使用 Book.vue 中的 $emit 传递数据:

<template>
  <div class="book" v-bind:class="{ 'is-read': book.read }">
    <p>{{ book.title }}</p>
    <p>{{ book.author }}</p>
    <input
      type="checkbox"
      v-on:change="$emit('update-book',book.id, book)"
      v-bind:checked="book.read"
    />
    <button @click="$emit('del-book', book.id)">x</button>
  </div>
</template>

If anyone could help me I'd really appreciate it.如果有人可以帮助我,我将不胜感激。

I just noticed my error.我刚刚注意到我的错误。 The db has an object which has an id and a book object inside.该数据库有一个 object,里面有一个 id 和一本书 object。 I was calling the object.read, and this was undefined.我正在调用 object.read,这是未定义的。 I should have set it to object.book.read.我应该将它设置为 object.book.read。

updateBook(object) {
  db.collection("books")
    .doc(object.id)
    .update({
      read: !object.book.read,
    })
    .then(() => {
      console.log("Book successfully updated!");
    })
    .catch((error) => {
      console.error("Error updating book: ", error);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM