尽管在组件中定义了 Vuex mapstate,但仍出现未定义的错误

Dan*_*ang 1 vue.js vuex

我无法让 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>
Run Code Online (Sandbox Code Playgroud)

有趣的是,如果我...mapState['coins']用一个实际的计算函数替换(见下面的代码),{{ coins }}工作。

coins() {
  return this.$store.state.coins;
},
Run Code Online (Sandbox Code Playgroud)

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

# 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),
});
Run Code Online (Sandbox Code Playgroud)

NaN*_*NaN 5

...mapState(['coins']),
Run Code Online (Sandbox Code Playgroud)

你忘了 ()