条件获取请求在vue中呈现子范围的子组件

时间:2018-03-05 09:05:01

标签: javascript vuejs2

当我点击(作者)组件的配置文件时,我无法弄清楚它应该如何呈现范围内的子组件,列出应用程序的主要实体,即所谓的fabmoments (用于3D打印信息的容器)。

我目前的解决方案如下:

export default {
  name: 'Multipe',
  props: [
    'author'
  ],
  data () {
    return {
    //   search: '',
      localAuthor: '',
      fabmoments: []
    }
  },
  created () {
    this.localAuthor = this.author
    if (typeof localAuthor !== 'undefined') {
      this.$http.get(`/users/${this.$route.params.id}/fabmoments`)
        .then(request => this.buildFabmomentList(request.data))
        .catch(() => { alert('Couldn\'t fetch faboments!') })
    } else {
      this.$http.get('/fabmoments')
        .then(request => this.buildFabmomentList(request.data))
        .catch(() => { alert('Couldn\'t fetch faboments!') })
    }
  },
  methods: {
    buildFabmomentList (data) {
      this.fabmoments = data
    } 
  },
  components: {
    // Box
  }
}

这将在配置文件中呈现所有内容,它应该将列表作为当前配置文件的作者的列表。

它在家中没有任何东西(没有接收道具),它应该渲染所有。

我不是JavaScript中的明星。我做错了什么?

更新

这可以作为解决方案,但不是很优雅。

export default {
  name: 'Multipe',
  props: [
    'author'
  ],
  data () {
    return {
      fabmoments: []
    }
  },
  created () {
    if (this.author.id >= 0) {
      this.$http.get(`/users/${this.$route.params.id}/fabmoments`)
        .then(request => this.buildFabmomentList(request.data))
        .catch(() => { alert('Couldn\'t fetch faboments!') })
    } else {
      this.$http.get('/fabmoments')
        .then(request => this.buildFabmomentList(request.data))
        .catch(() => { alert('Couldn\'t fetch faboments!') })
    }
  },
  methods: {
    buildFabmomentList (data) {
      this.fabmoments = data
    }
  },
  components: {
    // Box
  }
}

1 个答案:

答案 0 :(得分:0)

不确定哪个部分是错误的,但你可能会调试你的代码,找出为什么fabmoments是空数组,假设没有发生错误。

有三个部分需要调试:

  1. http响应 - 检查数据是否正确返回
  2. this - 检查this指针是否仍指向组件
  3. template - 检查fabmoments是否正确绑定到元素
  4. 最后,最好将http请求逻辑与组件分开。

    祝你好运!