IT이야기

라우터는 왜 이다.밀어서 안 되는 거야?[Vue3] [Vuex4]

cyworld 2022. 3. 26. 16:25
반응형

라우터는 왜 이다.밀어서 안 되는 거야?[Vue3] [Vuex4]

나는 Vue 3과 Vuex와 약간의 문제가 있다.내 Vuex 파일에 로그인했을 때 사용자를 리디렉션하려고 하는데 예상대로 작동하지 않아.오류를 반환하는 것이 아니라 링크를 변경하지만 다른 페이지로 리디렉션되는 것은 아니다.

내 행동은 이렇게 생겼어;

actions: {
        async login(commit: any, payload: any ) {
            const cookie_token  = useCookies();

            API.post('/login', {
                email: payload.email.value,
                password: payload.password.value
            })
                .then((response: any) => {
                    notif.success('Welcome back, ' + response.data.player.name)
                    cookie.set('user', response.data)
                    commit.commit('loginSuccess', response.data)

                    router.push({
                      name: 'index',
                    })

                }).catch((e) => (
                    console.log(e.message)
                )
            )
        }
    },

그리고 라우터는 루트가 정의된 곳에서 파일을 가져오고 있다.

그리고 여기 내 전체 라우터 파일이 있다.

import {
  createRouter as createClientRouter,
  createWebHistory,
} from 'vue-router'
import * as NProgress from 'nprogress'

// import routes from 'pages-generated'


import type { RouteRecordRaw } from "vue-router";

// Then we can define our routes
const routes: RouteRecordRaw[] = [
  // This is a simple route
  {
    component: () => import("/@src/pages/index.vue"),
    name: "index",
    path: "/",
    props: true,
  },
  {
    component: () => import("/@src/pages/auth.vue"),
    path: "/auth",
    props: true,
    children: [
      {
        component: () => import("/@src/pages/auth/login.vue"),
        name: "auth-login",
        path: "login-1",
        props: true,
      },
      {
        component: () => import("/@src/pages/auth/login.vue"),
        name: "auth-signup",
        path: "singup",
        props: true,
      },
    ],
  },
  {
    component: () => import("/@src/pages/[...all].vue"),
    name: "404",
    path: "/:all(.*)",
    props: true,
  },
];

export function createRouter() {
  const router = createClientRouter({
    history: createWebHistory(),
    routes,
  })

  /**
   * Handle NProgress display on-page changes
   */
  router.beforeEach(() => {
    NProgress.start()
  })
  router.afterEach(() => {
    NProgress.done()
  })

  return router
}

export default createRouter()

다른 파일에서 작동 중이고 라우터가 여기서 트리거되는 것을 알 수 있지만 페이지를 채우는 것이 아니라 vuex에서만 작동하지 않는다는 것을 명심하십시오.작동이 안 되는데 왜 오류가 없는 거지?

둘 이상의 Vue 라우터 인스턴스를 만드는 중.동일한 항목을 내보내십시오.router인스턴스(instance), 호출될 때마다 새 인스턴스를 생성하는 함수가 아님.

다음 코드는 원하는 결과를 산출할 가능성이 높다.

import {
  createRouter,
  createWebHistory,
} from 'vue-router'
import * as NProgress from 'nprogress'
import type { RouteRecordRaw } from "vue-router";

const routes: RouteRecordRaw[] = [
  // your routes here...
];

let router;

export function useRouter() {
  if (!router) {
    router = createRouter({
      history: createWebHistory(),
      routes,
    })

    router.beforeEach(() => {
      NProgress.start()
    })
    router.afterEach(() => {
      NProgress.done()
    })
  }
  return router
}

내가 배치한다.router외부 범위의 인스턴스(instance)를 호출할 때 항상 동일한 인스턴스(instance)를 얻으십시오.useRouter().
다음을 사용하여 사용:

import { useRouter } from '../path/to/router'
const router = useRouter();

참조URL: https://stackoverflow.com/questions/70333638/why-is-router-push-not-working-vue3-vuex4

반응형