简体   繁体   English

如何将JQuery AJAX函数转换为vue.js

[英]How to convert JQuery AJAX function to vue.js

I have the following AJAX function written in jQuery (just make AJAX call to get outcome for div A and div B - the example is simplified) 我有以下用jQuery编写的AJAX函数(只需进行AJAX调用即可获取div A和​​div B的结果-该示例已简化)

JavaScript JavaScript的

$(document).ready(function(){
    $( "#c" ).on( "click", function() {
        jQuery.ajax({
            type: "POST",
            url: "post.php",
            data: "",
            dataType:"JSON",
            success: function(data){
                if (data.status == 1){
                    $("#a").html(data.a);
                    $("#b").html(data.b);
                }
            }
        })
    })
})

HTML HTML

<div id="a"></div>
<div id="b"></div>
<button id="c">Start</button>

I understand how to make the HTML template for vue.js and how to set JavaScript variables, but how do I to set AJAX request for vue.js? 我了解如何为vue.js制作HTML模板以及如何设置JavaScript变量,但是我如何为vue.js设置AJAX请求?

Thank you. 谢谢。

Well, first thing first, you have to get rid of DOM Targeting with jQuery.In VueJS, there are no direct DOM manipulation. 首先,您必须使用jQuery摆脱DOM定位。在VueJS中,没有直接的DOM操作。 Next, you have to stop thinking jQuery way - Vue and jQuery are 2 totally different things which have different design pattern. 接下来,您必须停止思考jQuery方式-Vue和jQuery是2个完全不同的事物,它们具有不同的设计模式。

About your problem: 关于您的问题:

First you have to attach event listener on DOM Element 首先,您必须在DOM元素上附加事件侦听器

<button id="c" @click="ajaxMethod">Start</div>

Then into your Vue instance, you want to define that method, but before you make it, make sure you have jQuery installed 然后要在您的Vue实例中定义该方法,但是在创建该方法之前,请确保已安装jQuery

new Vue({
  el: '#app',
  data: {
   msg: 'hi';
  },
  methods: {
   ajaxMethod() {
    jQuery.ajax({
      // bla bla bla...
    })
   }
  }
})

But at the end, I won't to suggest you use jQuery here - there are much better libs such as Vue Resource and Axios. 但是最后,我不建议您在这里使用jQuery-还有更好的库,例如Vue Resource和Axios。

The suggested way is to use the axios library. 建议的方法是使用axios库。

<div id="app">  
  <div>{{a}}</div>
  <div>{{b}}</div>
  <button @click="retrieveData">Start</button>
</div>

Where the Vue instance is Vue实例在哪里

import axios from 'axios'
new Vue({
  el: '#app',
  data: {
    a: '',
    b: ''
  },
  methods: {
    retrieveData() {
      axios.post('post.php', {}, )
       .then(resp => {
         this.a = resp.data.a
         this.b = resp.data.b
       })
    }
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM