0

我知道stackoverflow中已经存在类似的问题,但我仍然不明白如何解决这个问题。我的控制台中有警告(查看标题)。

看警告

您可以通过以下代码重现警告

//index.js
import { createApp } from 'vue'
import { store } from './store'
import App from './App.vue'
import axios from 'axios';

const app = createApp(App)
app.__proto__.axios = axios
app.use(store)
app.mount("#app")

##App.vue

<template>
  <div class="TodoList">
    <p v-for="todo in todos" :key="todo.id">{{ todo.title }}</p>
  </div>
</template>

<script>
export default {
  mounted() {
    this.$store.dispatch("fillItems");
  },
  computed: {
    todos() {
      return this.$store.getters.todos;
    },
  },
};
</script>

<style>

</style>

##store.js

import { createStore } from 'vuex';

export const store = createStore({
    state: {
        todos: []
    },
    getters: {
        todos(state) {
            return state.todos
        }
    },
    mutations: {
        FILL_ITEMS(state, payload) {
            state.todos = payload
        }
    },
    actions: {
        fillItems({ commit }) {
            this.axios
                .get("https://jsonplaceholder.typicode.com/todos")
                .then(res => commit('FILL_ITEMS', res.data))
        }
    }
})
4

2 回答 2

2

您可以添加 axios 以便app.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")

编辑 vue 3 ts(分叉)

于 2020-12-01T12:56:21.967 回答
2

在 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
}

编辑: 我回答得太快了(感谢@BoussadjraBrahim),你不是在问组件,但我也会留下这个答案。如果您只想axios在单独的模块中使用,您可以像任何导入一样使用它:

import axios from 'axios';

并使用axios而不是this.axios

于 2020-12-01T12:45:40.470 回答