LoginSignup
25
27

More than 5 years have passed since last update.

Python + Django でVue.jsを使ってみる

Last updated at Posted at 2018-11-25

Vue.jsをDjangoで使ったときのメモ

1.主な環境

カテゴリ バージョンなど
os windows 10 home 64bit
python 3.6.5
django 2.0.7

2.アプリケーション

vuetestとします。

(1)ファイル構成

vuetest
│  admin.py
│  apps.py
│  models.py
│  tests.py
│  urls.py
│  views.py
│  __init__.py
│  
├─migrations
・・・
│          
├─templates
│  └─vuetest
│          index.html

(2)urls.py

urls.py
from django.urls import path
from . import views

app_name = 'vuetest'
urlpatterns = [
    # 書籍
    path('', views.index, name='index'),   # 一覧
]

(3)views.py

from django.shortcuts import render

# Create your views here.
def index(request):
    return render(request, 'vuetest/index.html',{'form_name': 'index'})

(4)index.html(失敗例)

index.html
{% extends 'commons/base.html' %}

{% load static %}

{% block links %}
  <script src="{% static 'js/vue.min.js' %}"></script>

{% endblock %}

{% block headertitle %}
Vue.js(これは失敗する例です。)
{% endblock %}

{% block content %}
</head>
<body>
  <div id="app">
    <p>{{ message }}</p>
    <br/>
  </div>
</body>

<script>

window.onload = function() {
  new Vue({
    el: '#app',
    data: {
      message: 'Hello Vue.js!',
      info: null
    },
  })
};
</script>
{% endblock %}

これで表示されるかな・・・と思ったら、ブラウザには何も表示されない。理由は簡単で、{{ message }}で、vueの変数を表示しようとしているが、この{{ }}は、Django Templateの予約記号でもある。

これを回避するために、Vue.jsのパラメータに「delimiter」を指定して、vue.jsの変数の予約記号を変更することで回避する。

変更後のhtmlは、以下のとおり。delimiterで指定した変数の開始記号、終了記号をhtml内に記述することで変数を表示することができる。

(4)index.html(変更後)

index.html
{% extends 'commons/base.html' %}

{% load static %}

{% block links %}
  <script src="{% static 'js/vue.min.js' %}"></script>
{% endblock %}

{% block headertitle %}
Vue.js
{% endblock %}

{% block content %}
</head>
<body>
  <div id="app">
    <p>[|[ message ]|]</p>
    <br/>
  </div>
</body>

<script>
window.onload = function() {
  new Vue({
    el: '#app',
    delimiters: ['[|[', ']|]'],
    data: {
      message: 'Hello Vue.js!',
    },
  })
};
</script>
{% endblock %}

変更後に表示される画面

image.png

25
27
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
27