如何将JSON数据从Django视图传递到Vue.js实例方法

5

我是Vue.js的新手。如何将JSON数据从Django视图传递到Vue实例(方法)中。

views.py

def articles(request):
    model = News.objects.all() # getting News objects list
    random_generator = random.randint(1, News.objects.count())
    context = {
              'title' : 'Articles' , 
              'modelSerialize' :  serializers.serialize('json',News.objects.all()),
              'num_of_objects' : News.objects.count() , 
              } 
    return render(request, 'articles.html',context)

VueScript.js

new Vue({

    el: '#list-Of-Articles-Displayed',
                data: {
                   count: 0
              },    
        ready: function() {


          this.$http.get('http://127.0.0.1:8000/article/').then(function (response) {
              response.status;
              console.log(response); 
          }, function (response) {
                  alert("error ");
              // error callback
          });

        }

        })

Template(article.html)

<div id = "list-Of-Articles-Displayed" class = "col-lg-10" v-for="news in loadArticles" >
<div class = "col-lg-11">
   <br>
   <a href = "<%news.id%>" ><%news.title%></a> 
   <h5><small><%news.date%></small></h5>
   <p>
      <%news.body%>...<span style = "color : purple" > <a href = "<%news.id%>"> Call to Action</a>
      <br><br></span> 
   </p>
</div>

我正在尝试在VueScript.js中访问JSON数据,但代替JSON数据,我得到了完整的HTML结构。有人能帮助我吗?谢谢。
3个回答

6
也许像这样:

视图.py

context = {'page_data' : json.dumps({"title": "Articles"})}

article.html

<body data="{{ page_data }}">

在Vue实例中。
beforeMount(){
  this.page = JSON.parse(document.getElementsByTagName('body')[0].getAttribute('data') || '{}');
}

3
也许你应该使用JsonResponse代替:
from django.http import JsonResponse

def articles(request):
    model = News.objects.all() # getting News objects list
    random_generator = random.randint(1, News.objects.count())
    context = {
              'title' : 'Articles' , 
              'modelSerialize' :  serializers.serialize('json',News.objects.all()),
              'num_of_objects' : News.objects.count() , 
              } 
    return JsonResponse(context)

你遇到的问题是,渲染函数返回了一个 content-type 为 text/html 的响应,而你需要的是一个 content-type 为 application/json 的响应,JsonResponse 是确保响应有正确 content-type 的快速方法。你可以在这里阅读更多关于 JsonResponse 的信息,或者阅读这个 StackOverflow 回答

1
我只获取JSON数据并在页面上显示。如何获取包含JSON数据的完整HTML页面? - light_ray

2

您可以将HTML添加到Vue组件中,并通过RESTful API提供JSON,例如使用Django Rest Framework。为了进行API调用,您需要在Vue中添加vue-router:

https://github.com/vuejs/vue-router

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接