2 回答

TA貢獻1821條經驗 獲得超6個贊
您可以添加 axiosapp.config.globalProperties
以便在任何子組件中訪問它:
const app = createApp(App)
app.config.globalProperties.axios=axios
在子組件中使用this.axios
但您無法在商店上下文中訪問它,因為this在操作中引用商店實例,因此您應該在商店文件中導入 axios 并使用它,如下所示:
import { createStore } from 'vuex';
import axios from 'axios';
export const store = createStore({
? ? state: {
? ? ? ? todos: []
? ? },
? ? getters: {
? ? ? ? todos(state) {
? ? ? ? ? ? return state.todos
? ? ? ? }
? ? },
? ? mutations: {
? ? ? ? FILL_ITEMS(state, payload) {
? ? ? ? ? ? state.todos = payload
? ? ? ? }
? ? },
? ? actions: {
? ? ? ? fillItems({ commit }) {
? ? ? ? ? ? axios
? ? ? ? ? ? ? ? .get("https://jsonplaceholder.typicode.com/todos")
? ? ? ? ? ? ? ? .then(res => commit('FILL_ITEMS', res.data))
? ? ? ? }
? ? }
})
或者您可以分配axios給商店實例(不建議特別使用打字稿):
const app = createApp(App)
store.axios = axios
app.use(store)
app.mount("#app")

TA貢獻1827條經驗 獲得超8個贊
在 Vue 3 中,您可以使用提供/注入為組件創建應用程序全局變量:
提供
import { createApp } from 'vue'
import { store } from './store'
import App from './App.vue'
import axios from 'axios';
const app = createApp(App)
app.provide('axios', axios);? // Providing to all components here
app.use(store)
app.mount("#app")
注射
在選項 API 中:
export default {
? inject: ['axios'];? ?// injecting in a component that wants it
}
在組合 API 中:
const { inject } = Vue;
...
setup() {
? const axios = inject('axios');? ?// injecting in a component that wants it
}
我回答得太快了,你不是在問組件,但我也會留下這個答案。如果您只想axios在單獨的模塊中使用,則可以像任何導入一樣使用它:
import axios from 'axios';
并使用axios而不是this.axios
添加回答
舉報