鍍金池/ 問答/HTML/ vuex 使用...mapState獲取到undefined

vuex 使用...mapState獲取到undefined

遇到的問題:
在vue中引入vuex,建立了store文件夾,并建立對應(yīng)的modules文件,在需要的vue文件中引入vuex的mapState方法,然而拿不到state,打印出來全部是undefined。
在控制臺中嘗試打印store對象發(fā)現(xiàn)state這個屬性似乎是被‘隱藏’了?

clipboard.png

如果一步步按照代碼路徑下去是能夠拿到我想要的state,但是這樣就和vuex應(yīng)該直接使用...mapState所能做到的相差甚遠(yuǎn)了。

詳細(xì)代碼:
store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import workIndex from './modules/projectManage/workIndex'

Vue.use(Vuex)
console.log('workIndex.state', workIndex.state)
const store = new Vuex.Store({
  modules: {
    workIndex
  }
})
export default store

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Vuex from 'vuex'
import App from './App'
import store from './store/index.js'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import './assets/css/common.css'
import './assets/css/base.css'
Vue.use(ElementUI)
Vue.use(Vuex)
console.log('store',store)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

modulels/projectManage/WorkIndex.js

// import Types from '../../types/projectManage/workIndexTypes'

const state = {
    testStoreData: '111'
}
const mutations = {
}

const actions = {
}

const getters = {
}

export default {
  /*
    namespaced: true,
    使用mapState的是,如...mapState('user', ['isLogin']),user為命名空間,可取到
    https://github.com/vuejs/vuex/pull/420
  */
  state,
  mutations,
  getters,
  actions
}

.vue文件

import {mapState} from 'vuex'
console.log('mapState',mapState)
export default {
  name: 'WorkIndex',
  data() {
        return {
            testData: '測試',
            searchform: {
                name: '',
                state: ''
            },
            checkFnModel: [],
        }
  },
    components: { headnav, WorkIndexHead },
    computed: {
        ...mapState(['testStoreData'])
    },

現(xiàn)在前端報錯是:

clipboard.png

請問是哪里出了問題?

clipboard.png
采用對象的形式我這里會報錯?

回答
編輯回答
焚音

store 要是new store()

2017年6月14日 18:46
編輯回答
憶當(dāng)年

用了modules之后,mapstate那樣寫找不到,要這樣寫,把對應(yīng)的module加上

...mapState({
  testStoreData: state => state.workIndex.testStoreData
})
2017年3月7日 00:04