The Startup
Published in

The Startup

Using Vue.js Alongside Django Template

A Demo App

Setup

<script src="<https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js>"></script>
<div id="vue-app">
[[ message ]]
</div>
var app = new Vue({
delimiters: ["[[", "]]"],
el: '#vue-app',
data: {
message: 'Hello Vue!'
}
})
  • el : stand for element, and it provides the Vue instance an existing DOM element to mount on.
  • Usually, we don’t need to define the limiters explicitly but here we need to because the default delimiters of Vue are the same as the default delimiter of Django, so we need to use something else for Vue and that’s why we’re using [[ ]] here instead of {{ }} .

Access Django Data from Vue

{{ django_variable | json_script:"js-data" }}
# todo/views.py
def home_view(request):
tasks = Task.objects.all()
context = {
'tasks': tasks,
}
return render(request, 'home.html', context)
Object of type QuerySet is not JSON serializable Django.
# todo/serializers.py
from rest_framework import serializers
from todo.models import Task
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = "__all__"
from django.shortcuts import render
from todo.models import Task
from todo.serializers import TaskSerializer
def home_view(request):
tasks = Task.objects.all()
context = {
'tasks': TaskSerializer(tasks, many=True).data,
}
return render(request, 'home.html', context)

Consuming APIs

<script src="<https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js>"></script>
<script>
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
</script>
var url = '/api/' + task_id + '/delete/';
axios
.delete(url)
.then(response => {
this.deleteTask(task_id)
})
.catch(error => {
console.log(error);
});

All done!

--

--

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +768K followers.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store