javascript - 我可以将 x-template 脚本导入 HTML 文件吗?

标签 javascript html vue.js vue-component

默认情况下,x-template(对于 Vue 组件)类似于

<script type="text/x-template" id="checkbox-template">
  <div class="checkbox-wrapper" @click="check">
    <div :class="{ checkbox: true, checked: checked }"></div>
    <div class="title">{{ title }}</div>
  </div>
</script>

现在我想将外部js文件链接到它,例如

<script type="text/x-template" id="checkbox-template" src="target.js" />

这可能吗?如果是这样,target.js 的语法是什么?

最佳答案

不,x-template必须是本地的。 <script>元素的srctype时属性被忽略属性不是module或 JavaScript MIME 类型,根据 MDN :

The embedded content is treated as a data block which won't be processed by the browser. Developers must use a valid MIME type that is not a JavaScript MIME type to denote data blocks. The src attribute will be ignored.

一些框架通过其他方式支持外部模板(即 templateUrl 等),但 Vue 不支持。这是 Evan You(Vue 创建者)的 explanation为什么:

it’s in fact much simpler if things are just in the same file. The context switching of jumping back and forth between two files actually makes the development experience much worse

the number of HTTP requests is still probably the most critical factor in your app’s initial load performance. Now imagine you use templateURL for every component in your app - the browser needs to perform dozens of HTTP requests before even being able to display anything

当然,您可以创建自己的加载程序来 AJAX 内容,就像您手动加载任何外部文件一样,无论内容如何,​​都作为字符串。或者您可以使用 Vue CLI,它使用类似的加载器。

关于javascript - 我可以将 x-template 脚本导入 HTML 文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64966732/

相关文章:

vue.js - 我可以动态地将计算属性插入到 Vue 组件中吗

vue.js - 使用 pwa 创建了 vue 应用程序,但找不到要编辑的 manifest.json

vue.js - 从 vue.js 中的商店获取的计算属性的 setter

javascript - jquery 的展开、折叠功能

javascript - 似乎没有得到 $().attr ('src' ) 来完成它的工作

javascript - 类似于 JqGrid 中用于表单编辑的 setCell

html - 在 child 悬停时,更改父容器的背景颜色(仅限 CSS)

javascript - 如何在 Spring MVC 4 和 HTML5 应用程序上添加带有 JS 和 CSS 的导入文件?

html - 移动设备网页最受支持的音频格式?

javascript - 排队变量动画