【问题标题】:Vuex map state undefined stateVuex 映射状态未定义状态
【发布时间】:2018-08-09 14:42:58
【问题描述】:

我试图在这里使用我的状态作为搜索查询传递,但是当使用地图状态拉下状态时,它返回“未定义”......我以前从未遇到过这个问题。

代码如下:

import Vue from 'vue'
import Hero from '../components/Hero/Hero'
import PopularDest from '../components/PopularDest/PopularDest'

import { mapActions, mapState } from 'vuex'

export default Vue.extend({
template: `
    <div class="page--sport">
        <hero :action="getSportData" page="sport" title="Sport Events"></hero>
        <div class="page--sport__bottom">
            <h2>Popular Sport Events</h2>
            <popular-dest></popular-dest>
        </div>
    </div>
`,
data () {
    return {
        searchQuery: {
            query: [(this as any).searchInput],
            genre: 'sport'
        }
    }
},
updated () {
   console.log(this.searchInput)
},  
components: {
    Hero,
    PopularDest
},
methods: {
    getSportData (): void {
        [(this as any ).getEventData(this.searchQuery)]
    },
    ...mapActions([
        'getEventData'
    ])
},
computed: {
    ...mapState([
        'searchInput'
    ])
}
})

我在这个项目中第一次使用 Vuex 模块,这似乎是我唯一的问题指标。

【问题讨论】:

标签: javascript vue.js vuex


【解决方案1】:

如果您使用的是基于模块的存储结构,显然您不能像这样直接访问 mapState 中模块的状态。例如,如果你这样做 - this.$store.state.searchInput 你会得到 undefined 但如果你这样做 this.$store.state.yourModuleName.searchInput 你会得到那个特定模块状态中的实际值。

您有两种方法可以解决此问题:

1.ma​​pState 中基于属性的访问

...mapState({
    searchInput: state => state.yourModuleName.searchInput,
  })

2.在模块中使用命名空间

..........
modules: {
yourModuleName: {
  namespaced: true,
.........

/* Using the namespace in mapState */
...mapState('yourModuleName',[
  'searchInput',
])

在 Vuex 的 github 页面上有一个未解决的问题 - https://github.com/vuejs/vuex/issues/459

【讨论】:

    猜你喜欢
    • 2020-09-10
    • 2020-05-28
    • 2018-09-22
    • 1970-01-01
    • 2019-12-11
    • 2021-02-01
    • 2020-06-21
    • 2019-03-10
    • 2021-06-08
    相关资源
    最近更新 更多