我无法让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),
});
答案 0 :(得分:3)
...mapState(['coins']),
您忘记了()