如何将数据变量从一个视图传递到另一个视图?

时间:2019-03-15 20:20:54

标签: vue.js

因此,我要做的就是在localUser视图更改为{{1}的路由Login后,从Login视图传递名为Home的变量},然后尝试在router.push("Home");视图及其组件中获取localUser的值。


我尝试过的事情: 我一直在尝试其他堆栈问题带来的各种解决方案,但是我无法使其正常运行,这肯定是我的错。我什至尝试使用道具传递数据,因为我真的很困,不知道该怎么办。

p.s。请原谅我的“新颖性”,因为这是我第三天开始使用我的第一个JS框架。


查看“登录”

Home
查看“主页”
<template>
  <div class="home">
    <div class="upperNav">
    <img class="v" alt="Vue logo" src="../assets/cbsc3-n4s6k.svg">
      <div v-if="localUser !== ''">
        <span>{{ localUser.displayName }}</span>
        <img class="pImg" :src="localUser.photoURL" alt="profile picture"/>
      </div>
    </div>

  </div>
</template>

<script>

import router from '../router'

import HelloWorld from '@/components/HelloWorld.vue';

export default {
  name: 'Login',
  components: {
    HelloWorld
  },
  data: function() {
    return {
      localUser: '',
      profileVisible: false,
    }
  },
  methods: {

    GoogleSignIn: function (event) {
      var provider = new firebase.auth.GoogleAuthProvider();
      firebase.auth().languageCode = 'en';


      firebase.auth().onAuthStateChanged( (user) => {
        if (user) {
          // If already signed in.
          console.log(user.displayName);
          this.localUser = user;
          console.log("Localuser:" + this.localUser.displayName)
          router.push("Home");
        } else {
          // If no one is signed in.
          firebase.auth().signInWithPopup(provider).then(function(result) {

                console.log("Logged in.");
                var token = result.credential.accessToken;
                var user = result.user;
                this.localUser = user;
                console.log("Localuser:" + this.localUser)

          }).catch(function(error) {
                var errorCode = error.code;
                var errorMessage = error.message;
                var email = error.email;
                // The firebase.auth.AuthCredential type that was used.
                var credential = error.credential;
                console.log(errorMessage);
          });

        }
      });
      let self = this;
    }
  },
  mounted() {
    console.log("Mounted");
    this.GoogleSignIn();
  }
}
</script>

1 个答案:

答案 0 :(得分:0)

如果您不想引入事件总线或类似vuex之类的东西,只需将其写入sessionStorage:

window.sessionStorage.setItem('localUser', JSON.stringify(this.localUser))

然后在Home

computed: {
 localUser: {
   get: function() {
     return JSON.parse(window.sessionStorage.getItem('localUser'))
   }
 }
}

现在Home可以在脚本中使用this.localUser,在SFC模板中可以使用localUser