简体   繁体   中英

Can I import x-template script into HTML file?

By default, x-template (for Vue component) is like

<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>

Now I want to link an external js file to it, like

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

Is it possible? If so, what's the syntax for target.js ?

No, x-template must be local. The <script> element's src attribute is ignored when the type attribute is anything other than module or a JavaScript MIME type, according to 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.

Some frameworks support an external template through other means (ie templateUrl , etc) but Vue doesn't. Here is Evan You's (Vue Creator) explanation for why:

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

Of course, you can create your own loader to AJAX the content just like you would load any external file manually, regardless of content, as a string. Or you can use the Vue CLI which uses a similar loader.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM