我想在由 fastApi 提供服务的应用程序中使用带有 cdn 的 Vue.js。
我在 index.html 和 app.js 中制作了一个没有快速 API 的原型(prototype),仅 cdn vue 两种组合都工作得很好,< em>按下按钮时计数。
然后我进入 fastApi 项目并与其模板机制协作使用。 app.js 似乎已加载。
但是似乎 vue 没有加载,因为变量 message 和 count 都无法识别(并且未显示在 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/