【问题标题】:Getting a not defined error despite Vuex mapstate being defined in components尽管在组件中定义了 Vuex mapstate,但出现未定义错误
【发布时间】:2019-03-04 12:00:25
【问题描述】:

我无法让 vuex mapState 函数正常工作。在我的文件 TheHeaderComponent.vue 中,我试图同时打印 {{ $store.state.coins }}{{ coins }} 但只有前者被打印,尽管我将 ...mapState['coins'] 传递到组件中。

显示的相关错误是vue.esm.js?a026:628 [Vue warn]: Property or method "coins" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

想知道是否有人可以阐明我应该做什么?

# TheHeaderComponent.vue
<template>
  <div>
    <p>{{ $store.state.coins }}</p>
    <p>{{ coins }}</p>
</template>

<script>
import {mapState} from 'vuex';

export default {
  name: 'TheHeader',
  computed: {
    ...mapState['coins'],
  },
  methods: {
  },
};
</script>

有趣的是,如果我将 ...mapState['coins'] 替换为实际的计算函数(请参见以下代码),{{ coins }} 可以工作。

coins() {
  return this.$store.state.coins;
},

我还包含了其他文件以供参考(仅相关代码)。

# mutations.js
export const setStudentId = (state, value) => {
  state.studentId = value;
};


export const setCoins = (state, value) => {
  state.coins = value;
};


# store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {
    coins: -1,
  },
  mutations,
});

# main.js
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';

Vue.use(Vuex);

import App from './App.vue';

import {store} from './store/store';

// allows us to use the vue debugger
Vue.config.devtools = true;

new Vue({
  el: '#app',
  store,
  // we pull information about user
  mounted: function() {
    axios
        .get('/api/v1/core/token/')
        .then((response) => {
          axios.defaults.headers.common['Authorization'] = 'Token '
            + response.data.token;
          this.$store.commit('setStudentId', response.data['student_id']);
        })
        // pulls basic information on student
        .then((response) => {
          return axios
              .get('/api/v1/core/student/' + this.$store.state.studentId);
        })
        .then((response) => {
          this.$store.commit('setCoins', response.data['coins']);
        });
  },
  render: (h) => h(App),
});

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:
    ...mapState(['coins']),
    

    你忘了()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      • 1970-01-01
      • 2012-03-15
      • 2018-08-17
      • 2016-06-01
      相关资源
      最近更新 更多