默认情况下,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>
元素的src
当type
时属性被忽略属性不是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/