javascript 我如何在全球范围内适用于皮尼亚州的行动?

xqkwcwgp  于 2023-02-21  发布在  Java
关注(0)|答案(1)|浏览(107)

如何全局应用于Pinia状态操作。我知道如何将数据(用户)作为属性发送到Vuex。但如何对Pinia执行类似操作。以及是否有方法全局完成Vue-router的类似问题?

methods: {
      submit(event: any) {
        event.preventDefault();
        let user = {
          firstName: this.firstName,
          lastName: this.lastName,
        }

        this.$store.dispatch('login', user)  // rewrite this line to Pinia
        this.$router.push('/');              // rewrite this line to Pinia

        this.firstName = '';
        this.lastName = '';
      }
    }
xj3cbfub

xj3cbfub1#

假设您想用pinia实现登录逻辑,下面是一个基本的示例:
stores/user.js

import { defineStore } from "pinia";
export const useStore = defineStore("user", {
  state: () => ({
    user: null
  }),
  actions: {
    login(user) {
      this.user = user;
    }
  }
});

Home.vue

<template>
  <h1>home</h1>
  <h2 v-if="user">Hello, {{ user.firstName }} {{ user.lastName }}</h2>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { useStore } from "@/stores/user";

const store = useStore();

const user = computed(() => {
  return store.user;
});
</script>

Login.vue

<template>
  <div>
    <form @submit.prevent="submit">
      <input type="text" id="firstName" v-model="firstName" />
      <input type="text" id="lastName" v-model="lastName" />
      <button type="submit">Submit</button>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useStore } from "@/stores/user";
import { useRouter } from "vue-router";

const firstName = ref("");
const lastName = ref("");
const store = useStore();
const router = useRouter();

const submit = () => {
  let user = {
    firstName: firstName.value,
    lastName: lastName.value,
  };

  store.login(user);
  router.push("/");
};
</script>

router.js中,如果用户未通过身份验证,您可以添加防护以重定向登录页面:

import { createRouter, createWebHistory } from "vue-router";
import Home from "@/views/Home.vue";
import Login from "@/views/Login.vue";
import { useStore } from "@/stores/user";
const routes = [
  {
    path: "/",
    name: "Home",
    component: Home
  },
  {
    path: "/login",
    name: "Login",
    component: Login
  }
];

const router = createRouter({
  history: createWebHistory("/"),
  routes
});

router.beforeEach((to, from, next) => {
  const store = useStore();
  const isAuthenticated = store.user !== null;

  if (to.name !== "Login" && !isAuthenticated) {
    next({ name: "Login" });
  } else {
    next();
  }
});

export default router;

相关问题