繁体   English   中英

[Vue 警告]:计算属性“axios”已在 Data.xml 中定义。 在<app></app>

[英][Vue warn]: Computed property “axios” is already defined in Data. at <App>

我知道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))
        }
    }
})

在 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

您可以将 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分配给商店实例(不建议特别使用 typescript):

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

编辑 vue 3 ts(分叉)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM