Vue中能否提取样式绑定对象实现跨组件复用?
能否提取Vue样式绑定对象到可复用文件?
完全可行,这是复用样式绑定逻辑的高效方案,而且没必要用.vue组件文件,直接用普通JS/TS模块实现会更简洁直观。
具体实现方式:
- 创建复用模块:新建一个
styleBindings.js(或.ts)文件,把所有样式绑定对象导出:
// src/utils/styleBindings.js export const flexColumn = { "d-flex": true, "flex-column": true, }; export const rowMB5 = { row: true, "mb-5": true, }; export const rowMT5 = { row: true, "mt-5": true, }; export const rowItemsCenter = { row: true, "align-items-center": true, }; export const fs08LightGrayish = { fontSize08Rem: true, colorLightGrayish: true, }; export const fs09LightGrayish = { fontSize09Rem: true, colorLightGrayish: true, }; export const blackishBold = { colorBlackish: true, "fw-bold": true, }; export const btnPrimary = { btn: true, "text-white": true, bgBluish: true, "fw-bold": true, fontSize09Rem: true, }; export const blueishBoldFs09 = { fontSize09Rem: true, "fw-bold": true, }; export const colMD2BlueishBold09 = { "col-md-2": true, colorBlueish: true, "fw-bold": true, fontSize09Rem: true, }; export const colMD3Fs08 = { fontSize08Rem: true, "col-md-3": true, }; export const colMd3FlexEvenlyCenter = { "col-md-3": true, "d-flex": true, "align-items-center": true, "justify-content-between": true, }; export const coldMD4flexColumnGap3 = { "col-md-4": true, "d-flex": true, "flex-column": true, "gap-3": true, }; export const colMD3FlexJustifyEndFs09Bold = { "col-md-3": true, "d-flex": true, colorBlackish: true, "justify-content-end": true, fontSize09Rem: true, "fw-bold": true, }; export const colMD4Fs08 = { "col-md-4": true, fontSize08Rem: true, }; export const colMD5UpcomingEvent = { "col-md-5": true, upcomingEvent: true, };
- 在组件中导入使用:在需要的组件里批量导入,然后通过
styles.xxx的方式绑定样式:
<script setup> import * as styles from '@/utils/styleBindings.js' </script> <template> <div :class="styles.flexColumn">垂直布局容器</div> <div :class="styles.rowMB5">底部间距5的行</div> <button :class="styles.btnPrimary">主按钮</button> </template>
关于用.vue文件的方案
如果坚持要用.vue文件,也能实现,但需要用defineExpose导出对象:
<!-- styles.vue --> <script setup> const flexColumn = { /* ... */ } // 其他样式对象... defineExpose({ flexColumn, rowMB5, // 列出所有要导出的对象 }) </script>
然后在其他组件中引用:
<script setup> import { ref } from 'vue' import Styles from './styles.vue' const stylesRef = ref(null) </script> <template> <Styles ref="stylesRef" /> <div :class="stylesRef?.flexColumn">...</div> </template>
不过这种方式需要额外渲染一个空组件,完全没必要,推荐直接用JS/TS模块的方案。
内容的提问来源于stack exchange,提问作者ahmad kharabsheh
相关产品推荐
相关产品推荐

