遇到的问题:
在vue中引入vuex,建立了store文件夹,并建立对应的modules文件,在需要的vue文件中引入vuex的mapState方法,然而拿不到state,打印出来全部是undefined。
在控制台中尝试打印store对象发现state这个属性似乎是被‘隐藏’了?
如果一步步按照代码路径下去是能够拿到我想要的state,但是这样就和vuex应该直接使用...mapState所能做到的相差甚远了。
详细代码:
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'])
},
现在前端报错是:
请问是哪里出了问题?
采用对象的形式我这里会报错?
用了
modules
之后,mapstate那样写找不到,要这样写,把对应的module加上