django vue js和Highcharts从JSON异步获取数据

时间:2018-06-24 02:36:02

标签: javascript python django vue.js highcharts

我目前正在使用django,highcharts和JQuery来构建一个简单的数据可视化Web应用程序。我只是从JQuery移到Vue Js,我对vue js如何从某些url获取JSON数据感到困惑。这是我的代码:

模板

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Django Highcharts Example</title>
</head>
<body>
  <div id="container" data-url="{% url 'async_chart_data' %}"></div>
  <script src="https://code.highcharts.com/highcharts.src.js"></script>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script>
    $.ajax({
      url: $("#container").attr("data-url"),
      dataType: 'json',
      success: function (data) {
        Highcharts.chart("container", data);
      }
    });
  </script>
</body>
</html>

Views.py

 def chart_view(request):
     return render(request,'chart.html')

 def chart_data(request):
     dataset = Passenger.objects.values('embarked')\
     .exclude(embarked='')\
     .annotate(total=Count('embarked'))\
     .order_by('embarked')

     port_name = dict()
     for choices_tuple in Passenger.PORT_CHOICES:
         port_name[choices_tuple[0]] = choices_tuple[1]

     #Hicharts visualization config
     pie_chart = {
        'chart' : {'type':'pie'},
        'title' : {'text' : 'PELABUHAN'},
        'series': [{
           'name' : 'Tempat Berangkat',
           'data' : list(map(lambda row: {'name' : port_name[row['embarked']],
            'y' : row['total']},dataset))
       }]
     }

     return JsonResponse(pie_chart)

Models.py

 from django.db import models

 class Passenger(models.Model):
       MALE = 'M'
       FEMALE = 'F'

      SEX_CHOICES = (
         (MALE, 'male'),
         (FEMALE, 'female')
       )

       CHERBOURG = 'C'
       QUEENSTOWN = 'Q'
       SOUTHAMPTON = 'S'

        PORT_CHOICES = (
           (CHERBOURG, 'Cherbourg'),
           (QUEENSTOWN, 'Queenstown'),
           (SOUTHAMPTON, 'Southampton'),
       )

      name = models.CharField(max_length=100, blank=True)
      sex = models.CharField(max_length=1, choices=SEX_CHOICES)
      survived = models.BooleanField()
      age = models.FloatField(null=True)
      ticket_class = models.PositiveSmallIntegerField()
      embarked = models.CharField(max_length=1, choices=PORT_CHOICES)

      def __str__(self):
         return self.name

我想更改JQuery用法以将JSON数据获取到Vue JS。我该怎么办?

编辑:我已经解决了这个问题。我在Here

上遇到另一个问题

1 个答案:

答案 0 :(得分:1)

案例已关闭。我可以通过使用vue js生命周期挂钩来实现。但是,它仍然足够慢以加载页面。需要(4到7秒),但可以。这是我的模板。

<!DOCTYPE html>
<html>
<head>
	<title>Using Vue Axios</title>
	<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
	<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
	<script src="https://code.highcharts.com/highcharts.src.js"></script>
</head>
<body>
	<div id="app">[[dataTitanic]]</div>
	<h1>The Chart Is Shown Below : </h1>
	<div id="container"></div>
	<script type="text/javascript">
		var url = "{% url 'async_chart_data' %}";
		var app = new Vue({
			delimiters : ['[[',']]'],
			el : '#app',
			data(){
				return {
					dataTitanic : null,
				}
			},
			mounted(){
				axios
				  .get(url)
				  .then(response => (this.dataTitanic = response['data']))
			},
			beforeUpdate(){
				Highcharts.chart('container',this.dataTitanic)
			}
		})
	</script>
</body>
</html>