【问题标题】:Getting x from remote sources and mirroring on to a list从远程源获取 x 并镜像到列表
【发布时间】:2017-01-31 20:44:55
【问题描述】:

目前我有这个,如果使用完整的应用程序,它将使用我选择的参数创建一个帖子,但是我对 vue.js 非常陌生,我的目标是能够拥有这样的文本文件(或其他方式存储(json等)值,然后让js脚本遍历文件并显示为卡片,例如在文件中我会有

"Mark", "http://google.com", "5556", "image"

或者当然使用 json 或类似的,我可以做到,但我的问题是,我不知道如何从远程源获取值并将其镜像到文档中,有人可以帮忙吗?清晰这里是我正在使用的代码的 sn-p

var app = new Vue({
  el: '#app',
  data: {
    keyword: '',
    postList: [

    new Post(
      'Name', 
      'Link', 
      'UID', 
      'Image'), 
    ]
  },
});

-- 编辑--

我要感谢用户 Justin MacArthur 的快速回答,如果您或其他任何人不介意回答我的另一个令人痛苦的无能问题。简单来说就是添加卡片的函数

var Post = function Post(title, link, author, img) {
  _classCallCheck(this, Post);
  this.title = title;
  this.link = link;
  this.author = author;
  this.img = img;
};

我现在可以从文本文件中获取数据,这意味着我可以这样做,并且假设我已经定义了响应(即 http 请求),它将输出文件的内容,我将如何为多张卡片执行此操作- 正如人们猜测的那样,为每张卡片中的每组四个变量中的每个变量设置一个新 URL 不仅乏味而且效率非常低。

new Post(
  response.data, 
)

【问题讨论】:

  • 我是否正确假设您要向服务器发出 AJAX 请求并让它返回值?作为文件或程序响应。
  • 没错,任何能让我获得所需响应并将它们添加到列表中的方法就足够了

标签: javascript json http vue.js vuejs2


【解决方案1】:

您正在寻找的解决方案是任何可用的 AJAX 库。 Vue 曾经推广 vue-resource,尽管它最近取消了对 Axios 的支持

您可以按照github页面上的说明将其安装到您的应用中,使用非常简单。

    // Perform a Get on a file/route
axios.get(
    'url.to.resource/path', 
    {
        params: {
            ID: 12345
        }
    }
).then(
    // Successful response received
    function (response) {
        console.log(response);
    }
).catch(
    // Error returned by the server
    function (error) {
        console.log(error);
    }
);

// Perform a Post on a file/route
// Posts don't need the 'params' object as the second argument is sent as the request body
axios.post(
    'url.to.resource/path', 
    {
        ID: 12345
    }
).then(
    // Successful response received
    function (response) {
        console.log(response);
    }
).catch(
    // Error returned by the server
    function (error) {
        console.log(error);
    }
);

显然,在 catch 处理程序中,您将获得错误处理代码,页面上显示警报或消息。在成功的过程中,您可以拥有类似于 this.postList.push(new Post(response.data.name, response.data.link, response.data.uid, response.data.image));

的东西

为了更容易,您可以像这样将 axios 分配给 vue 原型:

Vue.prototype.$http = axios

并使用本地虚拟机实例来使用它

this.$http.post("url", { data }).then(...);

编辑: 对于您的多重签名功能编辑,最好使用arguments 关键字。在 Javascript 中,引擎定义了一个 arguments 数组,其中包含传递给函数的参数。

var Post = function Post(title, link, author, img) {
  _classCallCheck(this, Post);

  if(arguments.length == 1) {
    this.title = title.title;
    this.link = title.link;
    this.author = title.author;
    this.img = title.img;
  } else {
    this.title = title;
    this.link = link;
    this.author = author;
    this.img = img;
  }
};

注意不要改变参数列表,因为它是参数本身的引用列表,因此您可以在不知情的情况下轻松覆盖变量。

【讨论】:

  • 感谢您的快速回答!,如果您不介意(并且不再觉得有义务帮助我而不是您已经拥有的),您是否介意帮助我一点点更多?,如果是,请检查编辑...
  • @TheDoctor 您的其他问题有一个快速编辑。
猜你喜欢
  • 1970-01-01
  • 2017-08-26
  • 2015-05-29
  • 1970-01-01
  • 2016-11-11
  • 2022-08-31
  • 2015-12-25
  • 1970-01-01
  • 2014-01-12
相关资源
最近更新 更多