Vue3 - 透過頁面刷新保持狀態
P粉959676410
P粉959676410 2024-03-25 23:22:06
0
1
470

我剛開始使用Vue3,並嘗試使用vuex來管理狀態。使用 Vue2 時,每次應用程式載入時我都會呼叫商店,如下所示:

// mains.js
import VueRouter from "vue-router";
import Vuex from "vuex";
import router from "./routes";

window.Vue = require('vue').default;
Vue.use(VueRouter);
Vue.use(VueMoment);
Vue.use(Vuex);

const store = new Vuex.Store(storeDefinition);

const app = new Vue({
    el: '#app',
    router,
    store,
    components: {
        "index": Index
    },
    async created() {
        this.$store.dispatch("loadStoredState");
        this.$store.dispatch("loadUser");
    },
});

這是我的 vuex 存儲,它定義了 vuex 的狀態、突變和操作:

// store.js
import { isLoggedIn, logOut } from "./shared/utils/auth";

export default {
    state: {
        isLoggedIn: false,
        user: {}
    },
    mutations: {
        setUser(state, payload) {
            state.user = payload;
        },
        setLoggedIn(state, payload) {
            state.isLoggedIn = payload;
        }
    },
    actions: {
        loadStoredState(context) {
            context.commit("setLoggedIn", isLoggedIn());
        },
        async loadUser({ commit, dispatch }) {
            if (isLoggedIn()) {
                try {
                    const user = (await axios.get("/user")).data;
                    commit("setUser", user);
                    commit("setLoggedIn", true);
                } catch (error) {
                    dispatch("logout");
                }
            }
        },
        logout({ commit }) {
            commit("setUser", {});
            commit("setLoggedIn", false);
            logOut();
        }
    },
    getters: {}
}

此檔案管理本機儲存的 cookie,該 cookie 儲存 isLoggedIn 的布林值:

// auth.js
export function isLoggedIn() {
    return localStorage.getItem("isLoggedIn") == 'true';
}

export function logIn() {
    localStorage.setItem("isLoggedIn", true);
}

export function logOut() {
    localStorage.setItem("isLoggedIn", false);
}

但是在 Vue3 中我正在建立這樣的 main.js 檔案:

// mains.js
const { createApp } = require('vue')
import Index from './Index.vue'
import createRouter from './router'
import { createStore } from 'vuex'
import storeDefinition from "./store";

const store = createStore(storeDefinition)

createApp(Index)
    .use(createRouter())
    .use(store)
    .mount('#app')

如何將管理商店的兩個呼叫加入到 createApp 函數中?

P粉959676410
P粉959676410

全部回覆(1)
P粉327903045

您可以使用 extends 選項將 created 掛鉤新增到根元件 a> 帶有元件定義:

// main.js
import { createApp } from 'vue'
import Index from './Index.vue'
import createRouter from './router'
import { createStore } from 'vuex'
import storeDefinition from './store'

const store = createStore(storeDefinition)

createApp({
    extends: Index,
    created() {
      this.$store.dispatch('loadStoredState')
      this.$store.dispatch('loadUser')
    },
  })
  .use(createRouter())
  .use(store)
  .mount('#app')

示範

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板