第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

楊魅力 2022-11-03 10:29:17
我的問題是,當(dāng)頁面重新加載時,中間件首先呈現(xiàn),然后是 vuex;因此,當(dāng)我想更改 vuex 中的值時,基于用戶是否經(jīng)過身份驗(yàn)證,中間件返回 vuex 的初始值。這意味著,如果用戶通過身份驗(yàn)證,它首先顯示 false,在渲染 vuex 之后,它再顯示 true。但是到那時,中間件已經(jīng)完成加載。這會導(dǎo)致在頁面刷新時將用戶重定向到登錄頁面。我的問題是,它們是我可以在中間件之前先加載 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貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超2個贊

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


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


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


所以在你的情況下,你需要在你的中間件中返回一個 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();

        }

    })

}

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


查看完整回答
反對 回復(fù) 2022-11-03
  • 1 回答
  • 0 關(guān)注
  • 106 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號