LoginSignup
0
2

VueとFlaskを連携させる

Last updated at Posted at 2023-12-22

こんにちは、mottyです。
簡単なVueとflask
いろいろ記事は見つかったのですが、諸々の場面で各論に入ったりで理解に時間がかかったので、シンプルな備忘録を書いていきます。

Vue側

超簡単なvue。
最終的にはVueは解釈され、プレーンなjavascriptに変換されます。

index.html
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask Vue.js Example</title>
</head>
<body>

<div id="app">
    <h1>{{message}}</h1>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            message: 'Hello, Vue.js!'
        }
    });
</script>

</body>
</html>

表示できましたね。

Flask側

先のhtmlをレンダリングする最小限の役割にとどめてます。

main.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

フォルダ構成

設定で変えられますが、デフォルトに従い下記で。

myflaskapp/
|-- templates/
|   |-- index.html
|-- venv/
|-- main.py

結果

http://127.0.0.1:5000にアクセスしましたが、タイトルだけ表示されてbodyには何も出ない・・・。
原因はVueとFlaskが解釈するマスタッシュ構文 "{{ msessage }}"が競合して、vue側がうまくレンダリングできなかったと考えられます。
v-textを用いて以下に直すと表示されるようになります。
(もちろんデフォルト設定を変えることもできます。)

<div id="app">
    <h1  v-text="message"></h1>
</div>

これで、flask側から立ち上げてもデータバインディングできました。

最後に

flask側とvue側、それぞれでデータを紐づけられていたら完成です。

index.html
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask Vue.js Example</title>
</head>
<body>
<h1>
    {{message_flask}}
</h1>

<div id="app">
    <h1  v-text="message"></h1>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            message: 'Hello, Vue.js!'
        }
    });
</script>

</body>
</html>
main.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    message_flask = 'Hello,Flask!'
    return render_template('index.html', message_flask=message_flask)

if __name__ == '__main__':
    app.run(debug=True)

表示:

20231223.PNG

最後に

バックエンドとフロントエンドの連携のための備忘録なので、フロントエンドのフレームワークのReactや、バックエンドでdjango、Laravel,Railsなどを使ったときなどの参考にもしたい。

0
2
0

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
0
2