有时候做一个简单的活动页, 使用构建工具显得太大材小用, 或者这个页面需要嵌入后端代码, 这时候我们就可以直接在html文件或者后端模板里写vue代码

直接写在html文件里:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Vue Demo</title>
    </head>
    <body>
        <div id="app">
            <div>Your name: {{ data.name }}</div>
            <div>Your pass: {{ data.pass }}</div>
        </div>
        <script type="importmap">
            {
                "imports": {
                    "vue": "https://cdn.jsdelivr.net/npm/vue@3.3.8/dist/vue.esm-browser.prod.js"
                }
            }
        </script>
        <script type="module" src="/assets/js/login.js"></script>
    </body>
</html>

写在后端模板文件里:

{% extends 'layout.twig' %}

{% import 'import/form.twig' as form %}

{% block content %}
    {% verbatim %}
        <template v-if="data">
            <div>Your name:
                {{ data.name }}</div>
            <div>Your pass:
                {{ data.pass }}</div>
        </template>
    {% endverbatim %}
    <form action="" method="post">
        {{ form.input('name', 'Your name', '请输入用户名', {class: 'superclass'}) }}
        {{ form.input('pass', 'Your pass', '请输入密码') }}
        <div class="form-group">
            <button @click.stop.prevent="handleSubmit" type="submit" class="btn btn-primary">Send</button>
        </div>
    </form>
{% endblock %}

{% block js %}
    <script type="importmap">
        {
            "imports": {
                "vue": "https://cdn.jsdelivr.net/npm/vue@3.3.8/dist/vue.esm-browser.prod.js"
            }
        }
    </script>
    <script type="module" src="/assets/js/login.js"></script>
{% endblock %}
// /assets/js/login.js

import { createApp, reactive, ref } from 'vue'

const $app$ = createApp({
    setup() {
        const form = reactive({
            name: '123',
            pass: '456',
        })
        const data = ref(null)

        const handleSubmit = () => {
            $.post('/api/contact', form, null, 'json').then((res) => {
                data.value = res.data
            })
        }

        return {
            form,
            data,
            handleSubmit,
        }
    },
}).mount('#app')

window.$app$ = $app$