簡體   English   中英

vue.js 2 - 將單個文件組件的 html 片段提取到獨立文件中

[英]vue.js 2 - extract html snipped of single file component into standalone file

我想知道是否有辦法將單個文件組件文件拆分為多個較小的文件。

我在說什么? 讓我們看看這個:

<template>
  ... 
</template>

<script>
  export default {
    name: 'my-component',
  };
</script>

<style scoped>
  ...
</style>

這就是典型的 vue.js 單文件組件的構建方式。 如您所見,有一個html -section( <template>標簽的內容)、一個javascript -section( <script>標簽的內容)和一個css -section( style標簽的內容)。 我想知道是否可以將所有這些部分拆分為單個文件。 我們稱它們為my-component.cssmy-component.es6my-component.html - 都“屬於” my-component.vue

我設法將javascript和css樣式提取到獨立文件中,如下所示:

<template>
  ...
</template>

<script src="./my-component.es6"></script>

<style scoped>
  @import './my-component.css';
</style>

這工作得很好。 現在我只剩下html部分了。 有沒有辦法也提取這個?

為什么?

我喜歡清晰的代碼分離,這是在my-component.vue文件中將“代碼混合”保持在最低限度的唯一方法。

這里的論點是什么是代碼分離。 Vue 的作者認為,在一個.vue文件中包含 HTML、CSS 和 JS 是將組件代碼分離到它們自己的位置並將它們的相關代碼保持在一起,並且與“關注點分離”無關。 在這里的文檔中簡要討論了它:

https://v2.vuejs.org/v2/guide/single-file-components.html#What-About-Separation-of-Concerns

所以你有3種不同的選擇:

  1. 按預期使用.vue文件。
  2. 使用 webpack 插件(在其他評論中提到)。
  3. 在不使用.vue文件的情況下構建您的組件,但是您將失去在開發過程中熱重載的能力,您將不得不使用html-loader插件。

HTML:

<div id="example">
  <my-component></my-component>
</div>

JS:

// register
Vue.component('my-component', {
  template: require('my-component.html');
})

// create a root instance
new Vue({
  el: '#example'
})

意見:只需使用.vue文件,如文檔中所示。 它會更容易維護,更容易找到你的代碼,而且你不必與 webpack 搏斗。 來自 Angular 世界,我覺得這有點奇怪,但我已經學會了喜歡它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM