【问题标题】:Send Ajax request after seen the element by user用户看到元素后发送 Ajax 请求
【发布时间】:2019-06-15 14:49:19
【问题描述】:

我想在用户看到一个元素后发送一个 ajax 查询。例如,有一个显示新闻列表的 ul 标记,在用户看到元素后,它会发送 ajax 查询以接收并在 ul 标记中显示新闻。

请注意,我使用的是 Vuejs 框架。

例如,像这样的:

<template>
    <div @WHEN_VIEWED="sendAjax">
        <ul v-if="news">
            <li v-for="new in news">{{ new.title }}</li>
        </ul>
        <div v-else>
            Please Wait...
        </div>
    </div>
</template>

<script>
  export default {
        name: "...",
        data() {
            return {
                news: null,
            };
        },
        methods: {
            sendAjax() {
                // Send Ajax...
            }
        }
    }
</script>

请帮忙,谢谢。

【问题讨论】:

    标签: javascript jquery html vue.js vuejs2


    【解决方案1】:

    使用lifecycle hooks 在组件生命周期内发出请求。

    对于您的问题,我建议 - mounted

    Mounted (DOM Is Ready and Placed inside the Page) 在你的组件被渲染到DOM 之后启动。

    它们允许您在第一次渲染之前和之后立即访问您的组件。但是,它们不会在服务器端渲染期间运行。

    供参考 - https://vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks

    <template>
        <div @WHEN_VIEWED="sendAjax">
            <ul v-if="news" v-for="new in news">
            </ul>
            <div v-else>
                Please Wait...
            </div>
        </div>
    </template>
    
    <script>
      export default {
            name: "...",
            data() {
                return {
                    news: null,
                };
            },
            mounted() {
              this.sendAjax()
            },
            methods: {
                sendAjax() {
                    // Send Ajax...
                }
            }
        }
    </script>
    

    【讨论】:

      【解决方案2】:

      try this
      
      <template>
          <div>
              <ul v-if="news.length">
                  <li v-for="new in news">{{ new.title }}</li>
              </ul>
              <div v-else>
                  Please Wait...
              </div>
          </div>
      </template>
      
      <script>
        export default {
              name: "...",
              data() {
                  return {
                      news: [],
                  };
              },
              methods: {
                  async sendAjax() {
                      // Send Ajax...
                  }
              },
              mounted() {
                this.$nextTick(() => {
                  this.news = await this.$axios.$get(`...`)
                })
              }
          }
      </script>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-18
        • 1970-01-01
        • 2020-04-05
        • 1970-01-01
        • 2018-04-27
        • 2020-07-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多