如何将以下代码转换为vue js代码?

时间:2017-11-14 08:35:11

标签: javascript jquery vue.js vue-component vue-router

     <script type="text/javascript">
    navigator.geolocation.getCurrentPosition(success, error);

    function success(position) {

        var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';

        $.getJSON(GEOCODING).done(function(location) {
            $('#country').html(location.results[0].address_components[5].long_name);
            $('#state').html(location.results[0].address_components[4].long_name);
            $('#city').html(location.results[0].address_components[2].long_name);
            $('#address').html(location.results[0].formatted_address);
            $('#latitude').html(position.coords.latitude);
            $('#longitude').html(position.coords.longitude);
        })
         $.ajax({
          url: 'post/filter/',
          data: {
            lat: position.coords.latitude,
            lon: position.coords.longitude,
          },
          type: "POST",
          dataType: 'json',

        });
    }

    function error(err) {
        console.log(err)
    }

这是我的代码。我需要将纬度和经度作为ajax请求传递给服务器端以获取值。通过使用此代码,我能够这样做。

我的vue js代码是

<div id="categorie">
  <div>{{vector.name}}</div>
</div>
<script>
categorie = new Vue({
    el: '#categorie',
    data: {
        vector: {},
    },
 methods: { 

            search_category: function success(position) {
              navigator.geolocation.getCurrentPosition(success, error);
            var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';

            $.getJSON(GEOCODING).done(function(location) {
                $('#country').html(location.results[0].address_components[5].long_name);
                $('#state').html(location.results[0].address_components[4].long_name);
                $('#city').html(location.results[0].address_components[2].long_name);
                $('#address').html(location.results[0].formatted_address);
                $('#latitude').html(position.coords.latitude);
                $('#longitude').html(position.coords.longitude);
            })
             var filter = {};
             var self=this;
             filter['category'] = position.coords.latitude;
            filter['subcategory'] = position.coords.longitude;
            $.ajax({
              "url": "post/filter",
               data: filter,
              dataType: "JSON",
              type: "POST",
              success: function(e) {
                  self.vector = e.data;
                console.log(e);
              },

            });
          }
        }

})
</script>

但是当我使用vue js代码时,我无法发送ajax请求?任何人都可以解决我的问题有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

处理问题的异步请求的vue方式如下所示:

this.$http.get(GEOCODING).then(response=> {
   // here your data is in response 
}).catch(error => {
   // TODO: handle your error here...
})

但要记住的是,vue-resource包中提供了上述功能。我建议你在@laracasts网站上查看this非常好的教程:https://laracasts.com/series/learning-vue-step-by-step/episodes/11

现在我希望你在vue中的异步请求中没有其他问题。你在vue js中的代码转换是在jsfiddle:https://jsfiddle.net/jcuytpx2/快乐编码:)

category = new Vue({
    el: '#category',
    data: () => ({
        vector: {},
        address: {
            country: '',
            state: '',
            city: '',
            address: ''
        },
    }),

    methods: {
        search_category(position) {
                navigator.geolocation.getCurrentPosition(position => {
                    var GEOCODING = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + '%2C' + position.coords.longitude + '&language=en';
                    this.google_response(GEOCODING).then(response => {
                        this.address.country = response.results[0].address_components[5].long_name
                        this.address.state = response.results[0].address_components[4].long_name
                        this.address.city = response.results[0].address_components[2].long_name
                        this.address.address = response.results[0].formatted_address

                        let filter = {}
                        filter.category = response.coords.latitude
                        filter.subcategory = response.coords.longitude

                        /**** implement your methods here....
				   this.$http.post('post/filter', filter).then(response => {
				   		this.vector = response.data
				   }).catch(error => {
				  		// TODO: Handle error here
				   })
				   *****/
                    }).catch(error => {
                        // TODO: Handle error here
                    })
                })
            },

            google_response(GEOCODING) {
                return new Promise((resolve, reject) => {
                    this.$http.get(GEOCODING).then(response => {
                        resolve(JSON.parse(response.bodyText))
                    }).catch(error => {
                        reject(error)
                    })
                })
            }
    }

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.3.4/vue-resource.min.js"></script>
<script src="https://unpkg.com/vue"></script>

<div id="category">
    <div>{{vector.name}}</div>
    <hr>
    <strong>
		Country: {{ address.country }}<br>
		State: {{ address.state }}<br>
		City: {{ address.city }}<br>
		Address: {{ address.address }}
	</strong>
    <hr>
    <button @click="search_category">
        Search
    </button>
</div>