首页 文章

映射到命名空间模块时,将prop作为模块名称传递

提问于
浏览
6

我正在尝试通过props将商店模块命名空间传递给组件 . 当我尝试使用道具映射到吸气剂时,它会抛出此错误,

Uncaught TypeError: Cannot convert undefined or null to object

如果我将名称作为字符串传递它是有效的 .

This Works

<script>
export default {

  props: ['store'],

  computed: {
    ...mapGetters('someString', [
      'filters'
    ])
  }
}
</script>

This does not work

this.store已定义
this.store typeof是一个String

<script>
  export default {

    props: ['store'],

    computed: {
      ...mapGetters(this.store, [
        'filters'
      ])
    }
  }
</script>

3 回答

  • 0

    我也解决了这个问题几个小时 . 然后我终于提出了一个想法 .

    • 在子vue组件中添加 attachStore 函数 . 函数nama并不重要 . 任何名称都可以,除了vue保留字 .
    export default {
      :
      attachStore (namespace) {
        Object.assign(this.computed, mapGetters(namespace, ['filters']))
      }
    }
    
    • 导入此vue组件时,使用namespace参数调用 attachStore . 然后在父组件属性中使用它 .
    import Child from './path/to/child'
    
    Child.attachStore('someStoresName')
    
    export default {
      name: 'parent',
      components: { Child }
      :
    }
    
  • 0

    请注意,在Vue的Github页面上也有关于此的讨论:https://github.com/vuejs/vuex/issues/863

    直到Vue正式支持它,我取代了类似的东西

    ...mapState({
      foo: state => state.foo
    })
    

    foo () {
      return this.$store.state[this.namespace + '/foo'] || 0
    }
    

    使用prop将 namespace 传递给我的子组件:

    props: {
      namespace: { type: String, required: true }
    }
    
  • -1

    您初始化过程中的错误, this.store 无法转换,因为它还没有使用命名空间,这是未经测试的,所以我不知道它是否可行,但您可以通过让它解决这个问题像这样的中间人:

    <script>
      export default {
    
        props: ['store'],
    
        data {
            namespace: (this.store !== undefined) ? this.store : 'null',
        },
    
        computed: {
          ...mapGetters(this.namespace, [
            'filters'
          ])
        }
      }
    </script>
    

    如果未定义 this.store ,则该三元表达式将返回一个字符串,如果未定义,那么它将返回 this.store 中的值 .

相关问题