1

我一直在寻找解决方法以在我的 Vuex 突变/操作上使用任何 http 客户端

我正在将 Vuex4 与 Vue3 和 Typescript 一起使用,这是我迄今为止尝试过的

src/plugins/http.ts

import { Plugin } from 'vue';
import rm from 'typed-rest-client';

const http: Plugin = {
  install(app, options) {
    app.config.globalProperties.$http = rm;

    app.provide('http', options);
  },
};

export default http;

src/main.ts

import { createApp } from 'vue';
import http from '@/plugins/http';
import App from '@/App';
import store from '@/store';

const app = createApp(App)
  .use(store)
  .use(http)
  .mount('#app');

然后尝试在突变或操作中从全局 this 访问 $http,但看起来无法从商店中检索 Vue 实例

另一个解决方法是在src/main.ts

store.$app = app;

Typescript 对不准备获取 $app 的 Store 界面不满意,也许有办法覆盖这种类型?

最后一个正在工作,但我不太喜欢这种用法。这个想法是向您的有效负载添加一个参数,该参数采用调用调度的当前 Vue 实例。看起来有点像这样

await this.$store.dispatch(ActionTypes.TEST, { app: this });

然后像这样在突变中使用它

async [MutationTypes.TEST](state, payload) {
  console.log(payload.app.$http); // Yaaay I get it !
},

如果你们知道另一种使用 Vuex 商店中的全局属性的方法,我会全力以赴!感谢阅读,希望有人可以帮助我!

4

0 回答 0