如何使用Nuxt在刷新时持续保持firebase-auth?

时间:2019-01-17 16:16:26

标签: javascript firebase firebase-authentication

我正在尝试设置Firebase身份验证,目前,用户可以注册并将我的信息存储在Vuex存储中。

如果刷新,我会丢失所有内容,而且我不知道如何在刷新过程中保持不变。我可以使用本地存储,Cookie,插件吗?我已经看过很多答案的最佳方式是什么,现在还不清楚。

我尝试使用中间件,但是没有运气。我也曾涉猎使用authStateChanged(),但不知道在哪里实现。

signup() {
  // checking if username exists within our database
  // creates a user through email and password
  if(this.username && this.email && this.password) {
      this.slug = slugify(this.username, {
          replacement:'-',
          remove: /[$*_+~.()'"\-:@]/g,
          lower: true
      })
      // is creating a variable that stores slug then checks whether it exists, if it does we send feedback
      let ref = db.collection('users').doc(this.slug)
      ref.get().then( (doc) => {
          if(doc.exists) {
              this.feedback ="This Username already exists"
          } else {
             firebase.auth().createUserWithEmailAndPassword(this.email, this.password)
              .then((cred) => {
                  console.log("below is CREDANTIALS")
                  console.log(cred.user)
                  ref.set({
                      username: this.username,
                      user_id: cred.user.uid
                  })
                  this.$store.commit('setUser', cred.user.uid)
                  this.$store.commit('setUsername', this.username)
                  // localStorage.setItem('user_id', cred.user.uid)
              })
              .then(() => {
                  this.$router.push({name: 'explore'})
              })
              .catch(err => {
                  console.log(err)
                  // err is caught by catch and has a property called message
                  this.feedback = err.message
              })
              }

          })
      }
  }

2 个答案:

答案 0 :(得分:0)

@TheWarderCoder嘿,这是保存到本地存储的代码段。

只需在方法内部创建一个函数。

   saveUserData(id) {
    localStorage.setItem('user-id', id)
   }

,并在注册方法中这样调用它。

   this.saveUserData(id)

好运!

答案 1 :(得分:0)

看看这个插件。 https://github.com/robinvdvleuten/vuex-persistedstate

Nuxt.js集成的用法如下:

<Viewbox Margin="5" MaxWidth="150" Stretch="Fill">
    <ColorPicker x:Name="myColorPicker"
     ColorSpectrumShape=”Ring”
     IsColorPreviewVisible="False"
     IsColorChannelTextInputVisible="False"
     IsHexInputVisible="False"
     />
</Viewbox>
    // nuxt.config.js

    plugins: [{ src: '~/plugins/localStorage.js', ssr: false }]