我应该如何格式化这个模拟JS数据,以便我可以在获取请求后使用它

时间:2017-03-27 19:44:52

标签: javascript ajax

我有一个收集ID的输入字段,应该使用该ID来查找相应的条目。以下是我目前所拥有的,底部是我想要的。

我可以获取文件的内容,但我无法用它做任何事情。

我现在有什么:

// mock-data.js
{
  id: "239491",
  name: "Big Bird",
  real: false,
  type: "Animal"
}

在我的Vue文件中,我使用axios进行GET来电

// search-file.Vue
axios.get('static/mock-data.js')
  .then((response) => {
    console.log(response.data)
  })
  .catch((error) => {
    console.error(error)
  })

这会注明看起来像是一个巨大的字符串,因为控制台中没有语法高亮显示。

我想拥有的是:

{
  entries: [
    "239491": {
      id: "239491",
      name: "Big Bird",
      real: false,
      type: "Animal"
    },
    "983502": {
      id: "983502",
      name: "Frodo",
      real: false,
      type: "Hobbit"
    },
    ...
    ...
  ]
}

我的Vue代码理想情况如下:

axios.get('static/mock-data/entries/' + userInput)
  .then((response) => {
    console.log(response.data)
  })
  .catch((error) => {
    console.error(error)
  })

我知道这不是正确的语法,但我找不到解决方案

1 个答案:

答案 0 :(得分:0)

如果您尝试创建用于测试目的的数据或没有阻止前端开发,为什么不直接调用它?我要做的是f



function mockDataService() {
  var mockData = {
    entries: [
      "239491": {
        id: "239491",
        name: "Big Bird",
        real: false,
        type: "Animal"
      },
      "983502": {
        id: "983502",
        name: "Frodo",
        real: false,
        type: "Hobbit"
      }
    ]
  };
  return {
    getMockDataById: function(id) {
      //return mock data by id
    }
  }
}


//you can mock out axios or just create a fake promise.
function callMockData(userInput) {
  return {
    then: function(success, failure) {
      success(mockDataService.getMockDataById(userInput))
    }
  }
}