[英]How to setup a store module using Vue3 with Vuex4 and TypeScript?
[英]this.$store is undefined in Vue3 with Vuex4 store and router
我正在尝试使用 Vuex4 商店设置 Vue3 应用程序,但我似乎无法在任何组件中访问该商店,总是出现一些未定义的错误。 我尝试了许多其他解决方案,但是当我 go 最终测试时,我似乎一直在循环运行,所以我觉得这是我所缺少的一些简单的东西。
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
}
存储/索引.ts:
import { createStore } from "vuex"
const store = {
state: () => ({
foo: "bar",
})
}
export default function () {
return createStore(store)
}
视图/仪表板.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>
您的设置似乎没问题,但是在组件上,您应该能够从选项 API 的内部export default
中获取存储。 如果使用合成,那么你需要这样做
import { useStore } from 'vuex'
export default {
setup () {
const store = useStore()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.