亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在渲染中間件之前如何在nuxt中渲染vuex模塊

在渲染中間件之前如何在nuxt中渲染vuex模塊

楊魅力 2022-11-03 10:29:17
我的問題是,當頁面重新加載時,中間件首先呈現,然后是 vuex;因此,當我想更改 vuex 中的值時,基于用戶是否經過身份驗證,中間件返回 vuex 的初始值。這意味著,如果用戶通過身份驗證,它首先顯示 false,在渲染 vuex 之后,它再顯示 true。但是到那時,中間件已經完成加載。這會導致在頁面刷新時將用戶重定向到登錄頁面。我的問題是,它們是我可以在中間件之前先加載 vuex 的一種方式嗎?這是中間件代碼;export default async function ({ store, redirect }) {  // If the user is not authenticated  const authenticated = await store.state.signup.authenticated  if (!authenticated) {    console.log(!authenticated)    return redirect('/login')  } else {    console.log('I am logged in')  }}這是vuex代碼;import axios from 'axios'export const state = () => ({  authenticated: false,  credential: null,})export const mutations = {  ADD_USER(state, data) {    state.credential = data    state.authenticated = true  },  LOGOUT(state) {    state.credential = null    state.authenticated = false  },}export const actions = {  async addUser({ commit }, data) {    try {      const response = await axios.post(        'http://localhost:8000/api/rest-auth/registration/',        data      )      commit('ADD_USER', response.data)      this.$router.push('/')    } catch (error) {      return console.log(error)    }  },  async addUserLogin({ commit }, data) {    try {      const response = await axios.post(        'http://localhost:8000/api/rest-auth/login/',        data      )      commit('ADD_USER', response.data)      this.$router.push('/')    } catch (error) {      return console.log(error)    }  },}export const getters = {  loggedIn(state) {    return !!state.credential  },}
查看完整描述

1 回答

?
一只斗牛犬

TA貢獻1784條經驗 獲得超2個贊

是的,有辦法做到這一點!事實上,商店已經在您的中間件中可用。但在你的情況下,商店是空的!您需要先獲取數據并填充存儲。


我建議你閱讀關于 nuxt 中間件的文檔https://nuxtjs.org/guide/routing#middleware。它指出


中間件可以是異步的。為此,只需返回一個 Promise 或使用第二個回調參數。


所以在你的情況下,你需要在你的中間件中返回一個 Promise :這個 Promise 將是 axios 請求。這是一個提議:


export default function ({ store, redirect }) {

    return new Promise(resolve => store.dispatch('signup/addUserLogin', data).then((user) => {

        if (!user) {

            // User not found

            redirect('/login');

        } else {

            // Do your stuff with the user freshly got, like commit in the store

            resolve();

        }

    })

}

在您的情況下,您應該修改操作addUserLogin:您應該只在此函數中獲取 axios 查詢,而不是重定向。此外,您將遇到操作中使用的數據、密碼和用戶的問題。刷新時,您會丟失此數據。您應該實現一個令牌系統,如 JWT,并將它們存儲在本地存儲或 cookie 中(如本示例中的https://nuxtjs.org/examples/auth-external-jwt/)。


查看完整回答
反對 回復 2022-11-03
  • 1 回答
  • 0 關注
  • 108 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號