首页 文章

在Vue和Vuex中的非子组件中获取商店值

提问于
浏览
0

我有一个Vuejs应用程序,它使用vue-router作为routeo,现在我想实现Vuex来管理同样的全局状态 . 问题是我无法使用商店,无论它如何集成或我如何尝试从组件中调用它,它只是不起作用 .

我只是在我的状态中有一个User对象,我有一个突变和一个影响该状态的函数 . 当我初始化Store时,我用我需要的信息加载它,并在vue-tools中正确显示信息,但是当我尝试从另一个组件访问该信息时出现问题 .

存储/ index.js

import Vue from 'vue';
import Vuex from 'vuex';

import actions from './actions';

Vue.use(Vuex);

const state = {
  user: {}
};

const mutations = {
  SET_ACTIVE_USER: (state, action) => {
    state.user = action.payload;
  }
};

export default new Vuex.Store({
  state,
  mutations,
  actions,
  strict: 'false'
});

存储/ actions.js

import axios from 'axios';

const actions = {
  getActiveUser({ commit }) {
    axios({
      method: 'GET',
      url: '/support/getUserData/',
      headers: {
        credentials: 'same-origin'
      }
    }).then(r => {
      commit('SET_ACTIVE_USER', {
        payload: r.data
      });
    }).catch(e => {
      console.error(e);
    });
  }
};

export default actions;

这是我对商店的实现,只需在App.Vue根组件中调用该突变即可在状态中进行更改并且正确完成 .

App.vue

<script>
import { mapActions } from "vuex";
import axios from "axios";

export default {
  name: "eol-app",
  methods: {
    ...mapActions(["getActiveUser"])
  },
  created() {
    this.getActiveUser();
  }
};
</script>

所以,在vue-tools中我观察到:

enter image description here

现在,我尝试进入商店并从另一个组件获取该数据,假设以下列方式在路径 /support/open 中,同时我尝试在我拥有的User对象中分配该商店的值 . 我的数据():

<script>
import { mapState, mapActions } from "vuex";

export default {
  name: "eol-ticket-open-list",
  data() {
    return {
      user: {}
    };
  },
  mounted() {
    this.user = this.getUser;
    this.getConsortiums();
  },
  computed: {
    getUser() {
      return this.$store.state.user;
    }
  }
};
</script>

在vue-tools中我观察到了这个:

enter image description here

但正如您所看到的,User对象是空的,我无法使用它 . 更糟糕的是,如果我尝试使用某个给我错误的用户值发出HTTP请求,显然是因为该对象为空 . 还尝试创建一个计算属性,我只返回用户的id,但它也不起作用,因为在这种情况下,返回的值是存储的默认值,而不是存储的值 . 商店有效 .

最后,如果需要,这是我的main.js文件:

import Vue from 'vue';
import router from './router';
import store from './store';
import Element from 'element-ui';
import locale from 'element-ui/lib/locale/lang/es';
import 'element-ui/lib/theme-chalk/index.css';

// Components
import App from './App';

// ElementUI Root Configuration.
Vue.use(Element, {
  size: 'small',
  locale
});

Vue.config.productionTip = false;

new Vue({
  el: '#app',
  store,
  router,
  components: {
    App
  },
  template: '<App/>'
});

欢迎任何帮助,因为我真的不明白我做错了什么,我不知道如何解决这个问题 . 谢谢!

1 回答

  • 0

    解决方案是Ber在原始问题的第一个评论中描述的解决方案,因为当他回答我的问题时它不是一个答案,所以它已经解决了 .

    简单地必须使用计算的属性,而不是将它们的值赋给我的copmonent中的数据中的属性或对象 .

相关问题