使用jQuery $ .getJSON()从Vuejs方法中的本地json文件获取数据 [英] Get data from local json file in Vuejs method using jQuery $.getJSON()
问题描述
我正在使用Vuejs开发一个演示应用程序,作为其中的一部分,我需要从本地.json文件中获取一些地图数据,获取其中的某些部分(例如经/纬度值),然后将其放入适当的数据对象中,以便可以在地图上显示它们.经过大量搜索之后,似乎是使用jQuery的$.getJSON()
方法的最简单方法.但是,我不知道如何从$.getJSON
回调中获取数据到我的Vue markers
对象.
I'm working on a demo app using Vuejs, and as part of it, I need to get some map data from a local .json file, get certain parts of it (such as lat/long values), and then put it into the appropriate data objects so they can be displayed on a map. After doing a lot of searching it seems that the easiest way it to use jQuery's $.getJSON()
method. However, what I can't figure out is how to get the data from within the $.getJSON
callback to my Vue markers
object.
这是我的相关代码:
<script>
import _ from 'lodash'
import $ from 'jquery'
export default {
name: 'HelloWorld',
data () {
return {
center: {lat: 37.541885, lng: -77.440624},
markers: []
}
},
methods: {
getMarkers: function () {
var apparatus = {}
var address = []
var description = {}
$.getJSON('../static/event1.json', function (data) {
// What do I do here to get outside of this function so
// I can manipulate it?
apparatus = data.apparatus
address = data.address
description = data.description
})
}
},
created () {
this.getMarkers()
}
}
</script>
正如您在上面的评论中看到的那样,我需要从$.getJSON
回调内部获取数据,但是我看不到需要执行的操作.这样会行得通吗,还是有更好的方法?
As you can see by the comment above, I need to get the data from inside the $.getJSON
callback, but I can't see what I need to do that. Will this way work, or is there a better way?
推荐答案
我不确定您要在函数外部访问哪个位置.
例如,您可以通过self.data = data
将$.getJSON
的结果分配给Vue的实例数据,然后可以在$.getJSON
I'm not sure where do you want to access this outside the function.
For example, you can assign result of $.getJSON
to Vue's instance data by self.data = data
, then you can access it outside of your $.getJSON
export default {
name: 'HelloWorld',
data () {
return {
center: {lat: 37.541885, lng: -77.440624},
markers: [],
data: null
}
},
methods: {
getMarkers: function () {
var apparatus = {}
var address = []
var description = {}
var self = this
$.getJSON('../static/event1.json', function (data) {
self.data = data // then you can access data outside of your function by reference this.data
// What do I do here to get outside of this function so
// I can manipulate it?
apparatus = data.apparatus
address = data.address
description = data.description
})
}
},
created () {
this.getMarkers()
}
}
这篇关于使用jQuery $ .getJSON()从Vuejs方法中的本地json文件获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!