Lastor
@Lastor
說
Wed, Jul 27, 2022 8:15 AM
coding
在研究騷操作,想把 handlebars 跟 Vue 3 做個結合,不知不覺下午快過完了
Lastor
@Lastor
說
Wed, Jul 27, 2022 8:15 AM
思路很單純,就是有一組商品清單,是靜態寫死的,不會透過打 API 獲得
Lastor
@Lastor
說
Wed, Jul 27, 2022 8:16 AM
如果我寫一支靜態 json,在 Vue 裡面 import 進來當作 data,之後該怎麼寫就這麼寫,不是難事
Lastor
@Lastor
說
Wed, Jul 27, 2022 8:16 AM
問題是這支 json 是所有 script 裡面最肥的一支,我不想包進去......
Lastor
@Lastor
說
Wed, Jul 27, 2022 8:17 AM
所以在想,可不可以先用模板引擎 render 出來,然後讓 Vue 去拿渲染好的 template
Lastor
@Lastor
說
Wed, Jul 27, 2022 8:17 AM
如果可以直接 render 到 .vue SFC 裡面就更完美了
Lastor
@Lastor
說
Wed, Jul 27, 2022 8:19 AM
大致編譯流程應該會是這感覺,我覺得理論上應該是可行的
handlebars -> render to html -> Vue bind target template
Lastor
@Lastor
說
Wed, Jul 27, 2022 8:20 AM
Vue 本能就能直接 bind 實體 DOM,可是要結合 build tool 似乎這操作太騷了,還沒研究出來
Lastor
@Lastor
說
Wed, Jul 27, 2022 8:20 AM
而且 Vue 2 跟 Vue 3 在這部分寫法很不一樣
Lastor
@Lastor
說
Wed, Jul 27, 2022 9:03 AM
============
好吧,姑且研究出一個做法,Vue2 的 inline-template 在 Vue3 被拿掉了,所以要把一個寫好的實體 DOM 綁給 Vue 組件要改用其他方法。Vue 文件上有兩招,第一招是用類似 Vue2 的 x-template,把 html 寫到 script 上
Inline Template Attribute | Vue 3 Migration Guide
Lastor
@Lastor
說
Wed, Jul 27, 2022 9:04 AM
直接在 index.html 上面用 script 標籤寫模板
Lastor
@Lastor
說
Wed, Jul 27, 2022 9:05 AM
然後在組件上用 template 屬性去指 id 就可以拿到內容 bind 上去
Lastor
@Lastor
說
Wed, Jul 27, 2022 9:06 AM
只是這有個坑,用 CDN 拉 Vue3 直接這樣寫是可以 work 的。但如果是走 npm 去 import vue,是不能執行的
Lastor
@Lastor
說
Wed, Jul 27, 2022 9:07 AM
會報一個警告說,當前版本不支持組件使用 template 屬性,要你拉別的版本:
[Vue warn]: Component provided template option but runtime compilation is not supported in this build of Vue. Configure your bundler to alias "vue" to "vue/dist/vue.esm-bundler.js".
at <App>
Lastor
@Lastor
說
Wed, Jul 27, 2022 9:08 AM
就照他警告說的,改拉 "vue/dist/vue.esm.bundler.js" 就可以了。可以直接在 import 關鍵字上改,也可以去改 vite alias 設定,都行
Lastor
@Lastor
說
Wed, Jul 27, 2022 9:09 AM
這種作法原則上是 Vue 搭配 build tool 的情況下,不推薦的寫法,硬要是可以,但就是很邪門歪道
Lastor
@Lastor
說
Wed, Jul 27, 2022 9:11 AM
同樣的做法,改寫成 SFC 也是可以 work 的,只是很不直觀是真的......
Lastor
@Lastor
說
Wed, Jul 27, 2022 9:12 AM
這樣感覺起來,要讓 handlebars 預先 render 好一組 template,如果這組內容不需要 Vue 上交互行為的化,可能直接拆開就不進 Vue app 會單純很多
載入新的回覆
handlebars -> render to html -> Vue bind target template
好吧,姑且研究出一個做法,Vue2 的 inline-template 在 Vue3 被拿掉了,所以要把一個寫好的實體 DOM 綁給 Vue 組件要改用其他方法。Vue 文件上有兩招,第一招是用類似 Vue2 的 x-template,把 html 寫到 script 上
Inline Template Attribute | Vue 3 Migration Guide
[Vue warn]: Component provided template option but runtime compilation is not supported in this build of Vue. Configure your bundler to alias "vue" to "vue/dist/vue.esm-bundler.js".
at <App>