Vue3 - 通过页面刷新保持状态
P粉959676410
P粉959676410 2024-03-25 23:22:06
0
1
476

我刚刚开始使用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')

演示

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板