【问题标题】:How can I get computed property from methods?如何从方法中获取计算属性?
【发布时间】:2017-05-01 01:49:46
【问题描述】:

首先,我使用this 模块在Vue 中进行无限加载。

为了在每次加载时添加元素,我将 json 数据从我的 API 服务器放入 数据对象,并在将数组拆分为“4”大小的组后再次将数组保存到变量中.但问题是它使用无法从计算机属性获取任何变量的方法事件处理程序附加元素。我对 Vue 很陌生,我找不到任何有关此的信息。这是代码!

 export default {
  name: 'main',

  data: () => ({
    items: [],
    line: []
  }),

  async created () {
    this.items = await fetch('/videos').then(res => res.json())
  },

  computed: {
      columns: function() {
          return chunk(this.items, 4)
      }
  },

  methods: {
    onInfinite() {
      setTimeout(() => {
        const temp = []
        const len = this.columns.length
        for (let i = len + 1; i <= len + 5; i++) {
          temp.push(this.columns[i])
          console.log(this.columns[i]) //It prints 'undefined'
        }

        this.list = this.list.concat(temp)
        this.$refs.myRefName.$emit('$InfiniteLoading:loaded')

      }, 700)
    },
  },
  components: {
    InfiniteLoading
  }
 }

【问题讨论】:

  • chunk 的代码是什么?
  • ime chunk 接受一个数组并返回每个长度为 n 的数组的数组,即“块”,所以我认为这就是这里发生的事情,但我不确定

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:
const len = this.columns.length // length of `columns` array

下一行:

for (let i = len + 1; i <= len + 5; i++) {
  ...this.columns[i]

您正在尝试访问数组长度以上的索引,这些值显然是未定义的。

您可能应该像这样遍历columns

for (let column of columns) {
   for (let item of column) { // asuming column is Array(4)
      console.log(item)

如果您的 columns 是一个包含 4 个元素的“块”数组,它应该可以工作。

【讨论】:

    【解决方案2】:

    你这个关键字来得到这样的计算方法:

    item.push(this.column[i]);
    

    【讨论】:

      猜你喜欢
      • 2022-08-18
      • 2018-07-13
      • 1970-01-01
      • 2021-03-13
      • 2018-11-27
      • 2020-10-02
      • 1970-01-01
      • 2019-08-12
      • 2018-03-02
      相关资源
      最近更新 更多