首页 > 解决方案 > Vue API 数据在窗口刷新时消失了

问题描述

当我登录时,我被重定向到需要 JWT 身份验证的秘密页面。数据加载在秘密页面上。当我刷新窗口时 - 数据丢失了。我该如何解决?

我使用 eventBus 将 JWT 令牌发送到同级模板。

提交时的登录视图方法:

submitSignin() {
      console.log("submit!");
      this.submitted = true;
      this.$v.$touch();
      if (this.$v.$invalid) {
        return; // stop here if form is invalid
      }
      axios
        .post("http://localhost:3000/auth/login", this.authData)
        .then((res) => {
          this.token = res.data.token;
          this.authData.email = "";
          this.authData.password = "";
          this.$v.$reset();
          this.successMsg = "You Sign in Successfully!";
          this.$router.push({ path: "/auth/all-users" });
          this.$nextTick(() => {
            eventBus.$emit("sendtoken", this.token);
          });
        })
        .catch((err) => {
          console.log(err.response.data.message);
          this.errorMsg = err.response.data.message;
        });
    },

SecretPage 视图:

<script>
export default {
  name: "SecretPage",
  data() {
    return {
      users: [],
    };
  },
  methods: {
    loadUsers() {
      let self = this;
      eventBus.$on("sendtoken", (token) => {
        axios
          .get("http://localhost:3000/auth/all-users", {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          })
          .then((response) => {
            console.log(token);
            console.log(response.data.users);
            self.users = response.data.users;
          })
          .catch((err) => {
            console.log(err);
          });
      });
    },
  },
  mounted() {
    this.loadUsers();
  },
};
</script>

加载用户

Windows 刷新后查看,但仍为登录状态

标签: vue.js

解决方案


推荐阅读