firebase PINIA商店(组成API)修改路线

xoshrz7s  于 2023-05-18  发布在  其他
关注(0)|答案(2)|浏览(97)

我正在使用:

vue@3.2.47
pinia@2.0.35
vue-router@4.1.6

我用firebase db创建了一个用于身份验证的存储库。代码如下:

import { defineStore } from 'pinia'
import { createUserWithEmailAndPassword,signInWithEmailAndPassword,signOut,onAuthStateChanged  } from "firebase/auth";
import { auth } from "@/firebase";

export const useStoreAuth = defineStore('storeAuth', {
  state: () => {
    return {
      user: null,
    }
  },
  actions: {
    init() {
      onAuthStateChanged(auth, (user) => {      
        if (user) {
          this.user = {}
          this.user.id = user.uid
          this.user.email = user.email
        } else {
          this.user = null
        }
      });
    },
    registerUser(credentials) {
      createUserWithEmailAndPassword(auth, credentials.email, credentials.password).then((userCredential) => {
        const user = userCredential.user 
        this.router.push('/')     
      }).catch((error) => {
        console.log('Error while registering:',error.message);
        }
      });
    },...

我正在使用这个.router.push,以便在成功注册后进入主页。
我想使用composite API重写我的代码,但当我这样做的时候,我不知道如何重写我的代码,以便函数registerUser(credentials)可以使用this.router.push。
我试着把它改写成这样:

const registerUser = (credentials) => {
    createUserWithEmailAndPassword(auth, credentials.email, credentials.password).then((userCredential) => {
      const firebaseUser = userCredential.user 
      router.push('/')     
    }).catch((error) => {
      console.log('Error while registering:',error.message);
      }
    });
  }

但在这种情况下它行不通。

ldxq2e6h

ldxq2e6h1#

在Composite API中,您可以将Router与useRouter一起使用

import { useRouter } from "vue-router";

const router = useRouter();

...andyourcode...

查看此页面,vue路由器官方站点。

atmip9wb

atmip9wb2#

可以将router作为registerUser()的参数传递
在您的组件中

import { useRouter } from "vue-router";
const router = useRouter();
...
registerUser(credentials, router);

在你店里

const registerUser = (credentials, router) => {
    createUserWithEmailAndPassword(auth, credentials.email, credentials.password).then((userCredential) => {
      const firebaseUser = userCredential.user 
      router.push('/')     
    }).catch((error) => {
      console.log('Error while registering:',error.message);
      }
    });
  }

相关问题