无法在vuex商店中访问axios

时间:2019-07-29 09:07:37

标签: javascript vue.js axios nativescript nativescript-vue

这是我的store.js代码:

import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios/dist/axios';
import VueAxios from 'vue-axios'

const api = axios.create({
  baseURL: 'mybase.com',
  timeout: 2000,
});

Vue.use(VueAxios, api)
Vue.use(Vuex);
export default new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',
  state: {
    name: null,
    YOB: null,
    gender: null,
    city: null,
    daily_goal: null,
    balance: null,
    today_video_count: 17,
    video_credit: 5,
  },
  mutations: {
    updateDailyGoal(state, value) {
      state.daily_goal = value;
    },
    addVideoCredit(state) {
      state.balance += state.video_credit;
    },
    reduceDonation(state, amount) {
      state.balance -= amount;
    },
    setVideoCount(state, count) {
      state.today_video_count = count;
    },
    initialize(state, profile) {
      state.name = profile.name;
      state.YOB = profile.YOB;
      state.gender = profile.gender;
      state.city = profile.city;
      state.daily_goal = profile.daily_goal;
      state.balance = profile.balance;
    },
  },
  actions: {
    submitVideoView({commit}, payload) {
      this.$http.post('/vid');
      commit('addVideoCredit');
    },
    setDailyGoal({commit}, value) {
      this.$http.post('/account/daily-goal', {daily_goal: value});
      commit('updateDailyGoal', value);
    },
    init({commit}) {
      this.$http.get('/account/profile').then(response => {
        commit('initialize', response);
      });
      this.$http.get('/account/vid-view').then(response => {
        commit('setVideoCount', response);
      });
    },
  },
  created() {
    dispatch('init');
  },
});

但是它给我的错误是undefined没有post属性,这意味着this。$ http没有定义。我怎样才能解决这个问题? 这也是我的main.js:

import Vue from "nativescript-vue";
import App from "./components/App";
import store from "./store";

new Vue({
  store,
  render: (h) => h("frame", [h(App)]),
}).$start();

任何对如何改进此代码的评论将不胜感激。我真的环顾四周,但是找不到任何好的文档来告诉我如何正确设置它。请注意,我只希望在每个用户会话/应用启动之初就调度一次init操作。

1 个答案:

答案 0 :(得分:1)

我认为您不需要仅将Axios包装器用于简单的HTTP请求。 您可以做的是将Axios模块导入文件中,然后直接通过Axios模块发出请求。 您可以根据需要将其包装为数据适配器。

import axios from 'axios';
const baseUrl = process.env.BASE_URL || '/';
export default {


 get(url, options) {
    return axios.get(`${baseUrl}${url}`, options)
      .then(response => response.data);
  },
  post(url, body, options) {
    return axios.post(`${baseUrl}${url}`, body, options)
      .then(response => response.data);
  },
  update(url, body, options) {
    return axios.put(`${baseUrl}${url}`, body, options)
      .then(response => response.data);
  },
  delete(url, options) {
    return axios.delete(`${baseUrl}${url}`, options);
  },
}

将该文件命名为EP / index.js例如 然后,当在vuex中时,您可以在下面导入该文件并使用这些功能,仅此而已。