Vue.js 在 fastapi 模板中无法识别(Vue.js in fastapi)

标签 vue.js fastapi

我想在由 fastApi 提供服务的应用程序中使用带有 cdn 的 Vue.js。

我在 index.htmlapp.js 中制作了一个没有快速 API 的原型(prototype),仅 cdn vue 两种组合都工作得很好,< em>按下按钮时计数。

然后我进入 fastApi 项目并与其模板机制协作使用。 app.js 似乎已加载。

但是似乎 vue 没有加载,因为变量 messagecount 都无法识别(并且未显示在 html 页面中),并且按下按钮也不会添加计数值。

有什么建议我的方法有什么问题吗?提前致谢。

项目结构。

/static
-/js
--/myapp.js
/templates
-/index.html
my_app.py

index.html的内容

<head>
    <meta charset="UTF-8">
    <title>Learning Vue</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    </script>
</head>
<body>
    <div id="app">
        {{ count }} = {{message}}
        <h1>Hello, Vue :) </h1>
        <button @click="push_button"> ok </button>
    </div>
    <script type="module"  src="{{ url_for('static', path='/js/app.js') }}"></script>
</body>

myapp.js

const app = Vue.createApp({
        data() {
            return {
                count: 100, message: "Hallo"
            }
        },
        methods: {
            push_button() {
                this.count++
            }
        }
    })
;

app.mount("#app")

my_app.py

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")

templates = Jinja2Templates(directory="templates")

@app.get("/", response_class=HTMLResponse)
async def get(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

最佳答案

发生这种情况是因为 Jinja2 使用的模板分隔符与前端的 Vue 相同。您可以像这样更改 vue 应用程序上的插值分隔符:

内部myapp.js:

<b>app.config.compilerOptions.delimiters = ['[[', ']]']</b>
app.mount("#app")

并更新index.html

<head>
    <meta charset="UTF-8">
    <title>Learning Vue</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    </script>
</head>
<body>
    <div id="app">
        <b>[[ count ]] = [[message]]</b>
        <h1>Hello, Vue :) </h1>
        <button @click="push_button"> ok </button>
    </div>
    <script type="module"  src="{{ url_for('static', path='/js/app.js') }}"></script>
</body>

关于Vue.js 在 fastapi 模板中无法识别(Vue.js in fastapi),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76085108/

相关文章:

javascript - Vuejs <keep-alive> 有什么意义?

python - FastAPI FileResponse 在 TempDirectory 中找不到文件

python - 通过 Postman 将 JSON 数据发布到 FastAPI 后端时,值不是有效的字典

nginx - FastAPI文档不适用于Nginx Ingress Controller

python - 如何覆盖 FastAPI 中 pydantic 验证错误的默认行为?

python-3.x - FastAPI - 调用API时设置response_model_exclude

javascript - 如何在 VueJS 应用程序中自定义 CKEditor 5

vue.js - 如何一次同时过渡两个元素?

javascript - 将数据从 Props 传递到 vue.js 中的数据

javascript - Vue.js 卡片中的某些项目没有反应性