gpt4 book ai didi

typescript - this.$store 在 Vue 3 中未定义,带有 Vuex 4 商店和路由器

转载 作者:行者123 更新时间:2023-12-05 05:35:45 24 4
gpt4 key购买 nike

我正在尝试设置一个带有 Vuex4 商店的 Vue3 应用程序,但我似乎无法在任何组件中访问该商店,总是出现一些未定义的错误。我已经尝试了许多其他解决方案,但当我进行最终测试时似乎一直在原地打转,所以我觉得这是我所缺少的简单东西。

main.ts:

import App from "./App.vue";
import { createApp } from "vue";
import createRouter from "@/router"
import createStore from "@/store"

const app = createApp(App);
const store = createStore();
const router = createRouter(app, store);
app
.use(store)
.use(router);

router.isReady().then(() => {
app.mount('#app');
});

路由器/index.ts:

import { createRouter, createWebHistory } from "vue-router"
import AppLayout from '../layouts/AppLayout.vue'
import { App } from 'vue';

export default function (app: App, store: any) {
const routes = [
{
path: "/",
component: AppLayout,
children: [
{
path: '',
component: () => import('../views/Dashboard.vue'),
},
{
path: 'accounts',
component: () => import('../views/Accounts.vue'),
},
]
},
]
const router = createRouter({
routes,
history: createWebHistory()
})

return router
}

商店/index.ts:

import { createStore } from "vuex"

const store = {
state: () => ({
foo: "bar",
})
}

export default function () {
return createStore(store)
}

views/Dashboard.vue

<script>
// ??? all some variation of undefined
// console.log(this.$store)
// console.log(this.store)
// console.log(store)

// import { useStore } from "vuex";
// const store = useStore();
// console.log(store)
</script>

最佳答案

你试过这样调试吗?

<script>
export default {
mounted() {
console.log(this.$store);
},
};
</script>

您的设置似乎没问题,但是在组件中您应该能够在 Options API 中从 export default 中获取存储。如果使用组合,那么你需要这样做

import { useStore } from 'vuex'

export default {
setup () {
const store = useStore()
}
}

关于typescript - this.$store 在 Vue 3 中未定义,带有 Vuex 4 商店和路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73423524/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com