A
A
Arti-Jack2018-04-23 23:56:26
Vue.js
Arti-Jack, 2018-04-23 23:56:26

How to render Vue components using data from the database?

Good day
To begin with, I would like to say that I am completely new to both django and vue.
I have the following task: I have implemented a backend, I need to write a frontend.
There are records in the database (the default in Django is SQLite), they need to be displayed. Records are component entities (Messages). That is, I need to display messages from the database and render it all (using vue). Moreover, it is necessary to display new messages every 10 seconds.
What is implemented in the backend:
There is a database of records, there is a message model (Message), there is a serializer, there is a view.
I think it would be appropriate to show the view code and urls, because this is the key point.
views:

from rest_framework import viewsets
from .models import Message
from .serializers import MessageSerializer

from rest_framework.views import APIView
from rest_framework.response import Response


# REST'full 
class MessageViewSet(APIView):
  # queryset = Message.objects.all().order_by('-created_at')
  # serializer_class = MessageSerializer
  def get(sefl, request):
    messages = Message.objects.all()
    serializer = MessageSerializer(messages, many=True)
    return Response(serializer.data)

  def post(sefl):
    pass	



def index(request):
   return render(request, 'webapp/index.html', {})

Urls:
from django.conf.urls import url, include
# from .views import index
#from .views import MessageViewSet

#urlpatterns = [
 #   url(r'^$', views.index, name='index'),

    # Test api 
  #  url(r'^api/test', views.test_api, name='test_api'),
#]


from rest_framework import routers
from .views import MessageViewSet

# Создаем router и регистрируем наш ViewSet
router = routers.DefaultRouter()
router.register(r'message', MessageViewSet)

# URLs настраиваются автоматически роутером
urlpatterns = [
  url(r'^$', MessageViewSet, name='message'),
  # url(r'^api/test', views.test_api, name='test_api')
]
 
urlpatterns += router.urls

from django.conf.urls import url, include
from django.contrib import admin
from rest_framework.urlpatterns import format_suffix_patterns
from webapp import views

urlpatterns = [
    # url(r'^$', include('webapp.urls')),
    # url(r'^api/v1/', include('webapp.urls')),
    url(r'^admin/', admin.site.urls),
    url(r'^message/', views.MessageViewSet.as_view())
]

urlpatterns = format_suffix_patterns(urlpatterns)

Here is the serializer code:
from rest_framework import serializers
from .models import Message

class MessageSerializer(serializers.ModelSerializer):
  class Meta:
    model = Message
    fields = ('id', 'text', 'readed')

When I enter the following url in the browser: http://127.0.0.1:8000/message/, this url is processed and a JSON representation of the records in the database is returned. For example:
[
 {
  "id": 1,
   "text": "First message.",
   "readed": false
 }
]

I need to render this case using Vue.
For this, I already have Vue components.
Message.vue
<template>
    <div class="message">
        <b-card class="mb-2">
        <p class="card-text">{{data.text}}</p>
        <p>{{data.msg_date}}</p>
            <b-button @click="readed">Прочитано</b-button>
        </b-card>
    </div>
</template>

<script>
    import axios from 'axios'
    export default {
        name: 'message',
        data () {
            return {
                data: {},
            }
        },
        methods: {
            readed: function() {
                console.log('Message readed')
                // ?...
            }
        }
    }
</script>

<style scoped>

</style>

And Messages.vue
<template>
    <div class="messages">
        <message 
          v-for='message in messages'
          v-bind:key="message.id"
        ></message>
    </div>
</template>

<script>
import axios from 'axios'
import Message from './Message'
    export default {
        name: 'messages',
        data () {
            return {
                messages: [1],
                data: {}
            }
        },
        mounted () {
            this.get_messages()
        },
        methods: {
            // FIXME:
            get_messages: function(){
                this.intervalid1 = setInterval(() => {
                    console.log('get')
                    this.messages.push('3')
                    axios.get(????)
                      .then((responce) => {
                      this.data = responce.data
                      })
                      .catch((error) => {
                      console.log(error)
                    })
                }, 10000)
            }
        },
        components: {
            Message
        } 
    }
</script>

<style scoped>
</style>

However, I'm not quite sure if this practice is correct. Therefore, the question is: how can I make it (based on the above) so that I have rendered Vue components (which are a message model), whose data is taken from the database?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nik_Set_7, 2018-04-25
@Nik_Set_7

Try to understand vuex
I have an idea what:
- actions to receive data are registered in vuex
- commit to save data
- getters to receive data
from the .vue component, refer to actions vuex
further in this.YourObject, enter data using getters,
then write data () {YourObject: this.YourObject}
everything, logically you got the newest data. And then output to html using v-for

J
JonGalt, 2018-05-10
@JonGalt

In axios, you must specify the full URL for which you want to get the data. In your case it is " 127.0.0.1:8000/message "
I understand that you have front and backend on different servers. In order for Vue to receive data on the backend, you need to use the django-cors-headers library for cross-domain requests. Without this, django won't give the data

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question