你如何动态导入 &将外部 HTML 模板解析为 Vue 组件? [英] How do you dynamically import & parse an external HTML template into a Vue component?

查看:73
本文介绍了你如何动态导入 &将外部 HTML 模板解析为 Vue 组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL;DR:

将主干/jquery 应用程序转换为 Vue 3.有超过 400 多个 html 模板文件用于不同的视图.希望能够以原始格式动态解析这些 html 模板,而无需进行大量重写.还希望能够在 html 中添加对 Vue 组件的模板引用,并让 Vue 解析它.

Converting a backbone/jquery app into Vue 3. Have over 400+ html template files for different views. Would like to be able to dynamically parse these these html templates in their original format, without having to do significant rewrite. Also would like to be able to add template references to Vue components in the html and have Vue parse that.

如何在 Vue 组件中定义外部或动态 HTML 模板(如 MyVueTemplate.html)?类似(伪代码):

How can you define an external or dynamic HTML template (like MyVueTemplate.html) within a Vue component? Something like (pseudo code):

export default {
    name: "MyComponent",
    template: import(`@/views/${this.html_id}.html`),
    props: {
        html_id: String,
    },
    components: {
    }
};

一旦成功,我需要能够让 temp.html 包含 Vue 组件的标签,例如 <MyOtherViewComponent variable1="test"></MyOtherViewComponent> 然后对其进行解析来自 Vue.

Once this works, I need to be able to have temp.html contain tags to Vue Components like <MyOtherViewComponent variable1="test"></MyOtherViewComponent> which is then parsed by Vue.

我希望 webpack import() 语句可以以与我们当前导入 html 模板相同的方式使用,但也可以在构建期间解析 Vue 组件引用.但如果需要,运行时编译也可以是(不太受欢迎的)选项.

I'm hoping that the webpack import() statement can be used in same way we are currently importing the html templates, but then also parse the Vue component references during build. But if need be, runtime compilation could also be a (less preferred) option.

有超过 400 个 html 文件,因此目前手动将它们全部重构为 Vue 组件是不可行的,因此采用这种方法.使用 Vue 3,但即使是 Vue 2 的解决方案也会为更多研​​究提供一个起点.

There are over 400 html files, so currently refactoring them all manually to Vue components wont be feasible, hence this approach. Using Vue 3, but even solutions for Vue 2 would offer a starting point for more research.

希望有人对这个问题有所了解.

Hope someone has some insight on this problem.

到目前为止,在旧的 html 中使用 Vue 组件的唯一方法是在 html 中添加标签,然后使用 createApp().mount() 为每个组件创建单独的 Vue 实例.不理想,但可能是唯一的方法.

So far it looks like the only way to be able to have Vue components within the old html, is to have tags in the html, and use createApp().mount() to create individual Vue instances for each of those components. Not ideal, but might be the only way.

推荐答案

您需要 运行时模板编译器 - 否则,如果您的模板是 Vue 组件,那么您可以通过 HTTP 加载它们,如 https://markus.oberlehner.net/blog/distributed-vue-applications-loading-components-via-http/

You need the runtime template compiler - otherwise, if your templates were Vue components then you could have been able to load them by HTTP as explained in https://markus.oberlehner.net/blog/distributed-vue-applications-loading-components-via-http/

这篇关于你如何动态导入 &amp;将外部 HTML 模板解析为 Vue 组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆