我想将我的 vue 组件拆分为包含 css (scss)、模板和代码的单独文件。到目前为止我得到的解决方案是:
js代码:
import Vue from 'vue';
import template from './template.vue';
import style from './style.vue';
import SubComponent from './SubComponent';
const component = {
components: {
SubComponent,
},
// other stuff like methods, watch ...
};
export default Vue.component('Component', {
...component,
...template,
...style,
});
The css:
<style lang="scss">
some-class {
background: green;
}
</style>
模板:
<template>
<div class="some-class">
<SubComponent />
</div>
</template>
我想知道这是否是这样做的方法,或者是否有更好/常见的方法来做到这一点。
作用域 CSS
对于作用域样式,我执行以下操作:
文件:style.module.scss
someClass {
background: green;
}
在 Component.js 中:
import Vue from 'vue';
import template from './template.vue';
import style from './style.module.scss';
import SubComponent from './SubComponent';
const component = {
components: {
SubComponent,
},
data: () => ({ style }),
// other stuff like methods, watch ...
};
export default Vue.component('Component', {
...component,
...template,
...style,
});
和 template.vue:
<template>
<div v-bind:class="[style.someClass]">
<SubComponent />
</div>
</template>
我不建议尝试以下操作:
<template src="./path/component.html" />
<script src="./path/component.vue" />
<style lang="scss" src="./path/component.scss />
The guide https://v2.vuejs.org/v2/guide/single-file-components.html#What-About-Separation-of-Concerns提供了一个示例,其中模板没有 src 属性here https://github.com/vuejs/vueify/issues/35#issuecomment-161436380Evan 是说你可以给它一个 src 属性,但看起来它坏了模块重新加载 https://stackoverflow.com/q/59610257/1641941.