user6827 user6827 - 1 month ago 75
Javascript Question

Using Vue with django

I've recently started on some social media web site using Django. Im using the default django template engine to fill my pages. But at this moment, I want to add javascript to make the site more dynamic. This means:


  • The header and footer is the same on each page. The header should have a dropdown menu, a search form that searches when you're typing.

  • My current django application has a base template that has the header and footer HTML, since every page should have this.

  • The site consists of multiple pages, think of index page, profile page, register page. Each of these pages have some common but also a lot of different dynamic components. For example the register page should have form validation on the fly, but the profile page doesn't need this. The profile page should have a status feed with infinite scrolling.



I want to use Vue to deal with the dynamic components, but I don't know how I should get started. The application should not be a SPA.


  • How should I structure the Vue code?

  • How should I bundle this. Using Gulp? Or maybe django-webpack-loader?

  • I should still be able to use the Django template tags, for example I want to be able to use
    {% url 'index' %}
    in the dropdown menu.


Answer

This looks like an opinion based question for which there is no clear answer.

You mentioned that you do not want the app to be a Single Page Application (SPA). If so, what is the motivation for using Vue? To handle user interactions within page?

Vue can work perfectly alright in non-SPA context. It will help you handle rich interactions within the page, like binding your data to drop-downs, forms, etc. But the real power of Vue comes out when you use it in SPA context.

For your case, I would recommend using Vue.js in standalone mode, where you can quickly define template within Vue components and write all your code easily in one javascript file.

Here is what you need: https://vuejs.org/guide/installation.html#Standalone

In "Vue.js standalone mode", There is no need for any webpack build system or vue-cli. You can build the app directly in your existing dev environment for django. gulp can optionally minify and bundle your javascript files normally, just like you do with your jQuery based apps.

Vue.js uses double curly braces {{..}} for templates, so it will not interfere with your django template strings.

All the jsFiddle examples for Vue.js run in standalone mode. That is precisely what you need at this moment. You may look at some of the recent questions with vue.js tag, find a sample jsFiddle and see how it is done.

For complex SPA apps, you need to build your Vue code separately from server side, test it thoroughly with dummy AJAX calls, build it for production and then drop the final production build into your server for end-to-end testing. This is something you can do in future.