【问题标题】:change data in Vuejs for all为所有人更改 Vuejs 中的数据
【发布时间】:2016-04-26 09:46:40
【问题描述】:

在 ajax totalUserPosts 返回零后我有这个问题,我不想要这个!

new Vue({
el: "#app",
data: {
  totalUserPosts:0,
},
methods:{
  getPostsAjax () {
    $.ajax({
      url:url,
      type: 'get',
      cache: false,
      dataType: "json",
      data:{
        limit: this.limit,
        id: this.vue_profile_id
      }
   }).done((data) => {
     this.userPosts = data.posts;
     this.totalUserPosts = data.total
   }.bind(this))
 },
 getUserPosts () {
   this.getPostsAjax()
   $(window).scroll(() => {
     if($(window).scrollTop() + $(window).height() > $(document).height() - 150) {
       console.log(this.totalUserPosts)
     }
   })
 }
})

我想在完成 ajax 请求后更改 totalUserPosts 请帮助我

【问题讨论】:

  • 能不能把console.log(this.totalUserPosts);在完成分配后的函数内部并告诉我们输出是什么?
  • 这个totalUserPosts的返回值=11
  • 这不是归零
  • 你试过在 done 函数中声明$(window).scroll 函数吗?
  • 有几个问题: 1) getPostsAjax() 是一个异步方法,所以scroll() 之后的代码在Ajax 调用完成之前就已经运行了。我的建议:使用 Promises 或实现一个回调,这样你就可以做到 getPostsAjax(cbFunctionHere) 2) 在回调内部 .scroll()this 不会指向 vue 实例。你应该使用普通函数并正确绑定它。

标签: javascript jquery ajax vue.js


【解决方案1】:

您在 ajax 函数返回之前调用滚动。您应该在 ajax 请求的回调函数中包含滚动功能,可能是这样的:

    new Vue({
    el: "#app",
    data: {
      totalUserPosts:0,
    },
    methods:{
      getPostsAjax () {
        $.ajax({
          url:url,
          type: 'get',
          cache: false,
          dataType: "json",
          data:{
            limit: this.limit,
            id: this.vue_profile_id
          }
         }).done(this.getUserPosts)
        },
         getUserPosts (data) {
           this.userPosts = data.posts
           this.totalUserPosts = data.total
           $(window).scroll(() => {
           if($(window).scrollTop() + $(window).height() > $(document).height() - 150) {
             console.log(this.totalUserPosts)
           }
          })
         }
        },
        ready () {
         this.getPostsAjax();
        }
    })

【讨论】:

  • 否 :( 这对我来说返回 undefined :( 你有另一个解决方案吗??
  • 究竟什么是未定义的?因为这就是我上面评论的目的。编辑:这个解决方案的问题是“this”有另一个上下文,因为我们在滚动事件上下文中。 @Jeff:您可以调整您的解决方案以使用变量而不是这个吗?
  • es16 箭头函数保持它们被写入的范围@TehSphinX
猜你喜欢
  • 2022-08-18
  • 2019-04-05
  • 2022-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-03
  • 2019-07-25
  • 2018-08-24
相关资源
最近更新 更多