【问题标题】:VueJs 2 doesn't invoke Ajax request in the "ready" functionVueJs 2 不在“就绪”函数中调用 Ajax 请求
【发布时间】:2017-08-12 13:54:51
【问题描述】:

这与Initializing Vue data with AJAX有关

我目前使用的是 Vue 2.2.4。我创建了一个 Vue 元素,并在“就绪”块内创建了 ajax 函数,就像上面的示例一样,但没有渲染任何内容。没有打印 console.log,表明这些 ajax 请求甚至没有被调用。有人知道发生了什么吗?假设我必须为此任务使用 jQuery ajax 库。

下面是我的代码:

var newJobsVue = new Vue({
    el: '#new-jobs',
    data: {
      jobs: []
    },
    methods: {
      ready: function () {
          var self = this;
          return $.ajax({
            method: 'GET',
            url: 'https://api.indeed.com/ads/apisearch',
            crossDomain: true,
            dataType: 'jsonp',
            data: {
              'v': '2', 
              'format': 'json', 
              'publisher': <My_Key>,
              q: 'javascript',
              l: '94112',
              userip: 'localhost',
              useragent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2)',
              latlong: '1'
            }
          })
          .done(function(response){
            //render the jobs from the search_response
            console.log("response is>>>>>", response.results);
            //nope, this is not actually logged
            self.jobs = response.results;
          })
          .fail(function(error){
            console.log("error is>>>", error);
            // neither is this one logged
          });
      }
    }
  });

【问题讨论】:

    标签: jquery ajax vuejs2


    【解决方案1】:

    你永远不会打电话给ready。试试

    var newJobsVue = new Vue({
        el: '#new-jobs',
        data: {
          jobs: []
        },
        methods: {
          ready: function () {
              // alot of code...
          }
        },
        mounted(){
            this.ready();
        }
      });
    

    【讨论】:

    • 注意ready()实际上是一个生命周期钩子,所以你可以像mounted()一样使用它。他可能只是混淆了方法和生命周期钩子。
    • @woutr_be 你的意思是在 Vue 1 中?
    【解决方案2】:

    您还可以使用created 挂钩或运行时间晚于beforeCreate 挂钩的挂钩来初始化数据:beforeMount, mounted在 created 钩子中,您将能够访问方法、反应数据和活动的事件,而在 beforeCreate 钩子中,您无法访问您的数据和方法。

    简介:使用 created hook 如果您想尽早初始化您的数据使用晚于 beforeCreate hook 运行的 hooks 来初始化您的数据

    var newJobsVue = new Vue({
        el: '#new-jobs',
        data: {
          jobs: []
        },
        methods: {
          ready: function () {
              your ready function
          }
        },
    
        created(){ // can also be replace with beforeMount and Mounted
            this.ready();
        }
      });
    

    参考:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 2020-08-03
      • 2011-03-10
      相关资源
      最近更新 更多