【问题标题】:How can I run functions within a Vue data object?如何在 Vue 数据对象中运行函数?
【发布时间】:2017-06-05 10:43:15
【问题描述】:

所以我尝试在 Vue JS 中使用以下组件:

Vue.component('careers', {
  template: '<div>A custom component!</div>',

  data: function() {

    var careerData = [];

    client.getEntries()
    .then(function (entries) {
      // log the title for all the entries that have it
      entries.items.forEach(function (entry) {
        if(entry.fields.jobTitle) {
          careerData.push(entry);
        }
      })
    });

    return careerData;
  }
});

以下代码会发出类似这样的错误:

[Vue warn]: data functions should return an object:
https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function 
(found in component <careers>)

但是,如您所见,我正在通过我的所有 Contentful entries 运行 foreach,然后条目中的每个对象都被推送到数组中,然后我尝试返回数组,但出现错误。

知道如何将我的所有entries 提取到组件内的数据对象中吗?

当我在 Vue 组件之外使用 client.getEntries() 函数时,我得到以下数据:

【问题讨论】:

  • 错误表示数据函数必须返回Object,而不是Array

标签: javascript vue.js vue-component


【解决方案1】:

第一件事 - 保持你的数据模型尽可能干净 - 所以那里没有方法。

第二件事,正如错误所说,当您将数据处理到组件中时,数据应该是返回对象的函数:

Vue.component('careers', {
  template: '<div>A custom component!</div>',

  data: function() {
    return {
     careerData: []
    }
  }
});

在我写的时候,数据获取和其他逻辑不应该在数据中,在 Vue.js 中有一个为此保留的对象,称为 methods

所以将你的逻辑移到方法中,当你收到数据后,你可以像这样将它分配给careerData

this.careerData = newData

或者像以前一样将东西推送到数组中。最后,您可以在一些生命周期挂钩上调用该方法:

Vue.component('careers', {
  template: '<div>A custom component!</div>',

  data: function() {
    return {
      careerData: []
    }
  },

  created: function() {
    this.fetchData();
  },

  methods: {
    fetchData: function() {
      // your fetch logic here
    }
  }
});

【讨论】:

  • 啊,这对我来说更有意义了。感谢您传播知识!
【解决方案2】:

有时你不得不在数据对象中包含函数,例如在将数据和函数发布到某些框架组件时(例如 element-ui shortcuts in datepicker)。因为vue中的data其实是一个函数,所以可以在return语句之前在里面声明函数:

export default {
data() {
  let onClick = (picker) => {
    picker.$emit('pick', new Date());
    this.myMethod();
  }

  return {
    pickerOptions: {
      shortcuts: [{
        text: 'Today',
        onClick: onClick
      }]}
  };
},
methods:{
  myMethod(){
    console.log("foo")
  }
},
};

如果你愿意,你可以用这个指向方法。它不是特别干净,但有时可能会派上用场。

【讨论】:

    猜你喜欢
    • 2015-11-06
    • 2023-03-28
    • 1970-01-01
    • 2015-04-19
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多