【问题标题】:vue.js 2 - extract html snipped of single file component into standalone filevue.js 2 - 将单个文件组件的 html 片段提取到独立文件中
【发布时间】:2018-07-18 04:08:31
【问题描述】:

我想知道是否有办法将Single File Components 文件拆分为多个较小的文件。

我在说什么? 让我们看看这个:

<template>
  ... 
</template>

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

<style scoped>
  ...
</style>

这就是典型的 vue.js 单文件组件的构建方式。如您所见,有一个html-section(&lt;template&gt; 标签的内容)、一个javascript-section(&lt;script&gt; 标签的内容)和一个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 文件中将“代码混合”保持在最低限度的唯一方法。

【问题讨论】:

  • @Veehmot 我一直在寻找相关问题,但找不到任何问题。谢谢,我去看看
  • 有一个 webpack 插件。可能有助于减少自己处理这一切的工作。 github.com/pksunkara/vue-builder-webpack-plugin
  • 就我个人而言,我喜欢相反的方式——把所有东西都放在一个地方,但是是的,我也能理解你的愿望。那么为什么要使用单个文件组件 - 为什么不只是去“老派”并单独编写它(然后在需要时使用 Webpack 或其他东西打包)?
  • @nettutvikler 因为我喜欢单文件组件的概念。并作为补充;我对 webpack 的经验非常有限。 ..

标签: html vue.js vuejs2 vue-component code-separation


【解决方案1】:

这里的论点是什么是代码分离。 Vue 的作者认为,在一个.vue 文件中包含 HTML、CSS 和 JS 是将组件代码分离到它们自己的位置并将它们的相关代码保持在一起,并且与“关注点分离”无关。此处的文档中对此进行了简要讨论:

https://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 世界,我觉得这有点奇怪,但我学会了喜欢它。

【讨论】:

  • 我明白了。文档可能不打算分离 .vue 组件,但对我来说这是提高代码质量的额外步骤。此外,首先拥有单个文件组件的好处不会因为将其拆分为 3 个文件而丢失,这个概念只是更进一步。但我接受你的回答,让我对情况有了一个好主意
猜你喜欢
  • 2019-07-10
  • 1970-01-01
  • 2018-02-15
  • 1970-01-01
  • 2019-10-29
  • 1970-01-01
  • 1970-01-01
  • 2017-10-07
  • 2012-06-21
相关资源
最近更新 更多