gpt4 book ai didi

javascript - Firebase - Vue 数据库集成不起作用

转载 作者:行者123 更新时间:2023-12-04 12:54:10 28 4
gpt4 key购买 nike

我正在尝试将 Firebase 与 Vue 4 应用程序集成,目前出现以下错误。

Uncaught TypeError: db__WEBPACK_IMPORTED_MODULE_1_.default.database is not a function


我在用
“火力基地”:“^9.0.0”
“vue”:“^3.0.0”

import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";


const firebaseConfig = {
// keys
};

const app = initializeApp(firebaseConfig);

const db = getDatabase(app);

export {db}

我的函数调用如下

import {reactive} from 'vue';
import { ref, set, push } from "firebase/database";
import {db} from "./db"


export default {
setup(){
const inputUsername = ref("");
const inputMessage = ref("");
const state = reactive({
username: "",
messages:[]
});

const Login = () =>{
if(inputUsername.value != "" || inputUsername.value != null){
state.username = inputUsername.value;
inputUsername.value = "";
}
}
const SendMessage = () => {
// const messagesRef = db.database().ref("messages");
if (inputMessage.value === "" || inputMessage.value === null) {
return;
}
const message = {
username: state.username,
content: inputMessage.value
}
set(push(ref(db, 'messages')), message);

// messagesRef.push(message);
inputMessage.value = "";
}
return{
inputUsername,
Login,
state,
inputMessage,
SendMessage
}
}
}

我尝试了以下 the following suggestion 但它没有用。
谢谢!

最佳答案

新的模块化 SDK 不再使用命名空间。所以你不能使用app.database() .您可以简单地从初始化 Firebase 的文件中导出数据库实例,如下所示:

import { initializeApp } from "firebase/app";
import { getDatabase } from "firebase/database";

const app = initializeApp(firebaseConfig);

const db = getDatabase(app);

export {db}
然后在需要的地方导入并使用它:
import { ref, child, get } from "firebase/database";
import {db} from "../path/to/firebase.js"

const message = {
username: state.username,
content: inputMessage.value
}

set(push(ref(db, 'messages')), message);
您可以在 documentation 中了解有关新语法的更多信息。

Uncaught TypeError: db._checkNotDeleted is not a function


此错误是由于您正在导入 ref来自 firebasevue .请导入 Firebase 的 reffireRef .
import { reactive, ref } from "vue";
import { ref as fireRef, set, push } from "firebase/database";
import { db } from "./db";

// usage
set(push(fireRef(db, "messages")), message);

关于javascript - Firebase - Vue 数据库集成不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68997481/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com