css-module
在 Vue 中使用 CSS Modules,需要進行以下步驟:
- 首先在你的 Vue 組件中,你需要在
<style>標籤中添加module屬性,如下:
<style module>
.button {
color: blue;
}
</style>
- 然後在你的 Vue 組件的
<template>部分,你可以通過$style來訪問你的 CSS 模組,如下:
<template>
<button :class="$style.button">點我</button>
</template>
- 如果你的 CSS 類名包含中劃線或其他特殊字符,你可以使用中括號語法來訪問它,如下:
<style module>
.button-clicked {
color: red;
}
</style>
<template>
<button :class="$style['button-clicked']">點我</button>
</template>
- 你也可以在你的 JavaScript 部分訪問你的 CSS 模塊,如下:
<script>
export default {
computed: {
buttonClass() {
return this.$style.button;
}
}
}
</script>
- 如果你想在同一個組件中使用全局 CSS 和 CSS Modules,你可以使用兩個
<style>標籤,一個帶有module屬性,另一個不帶,如下:
<style>
/* 全局 CSS */
.global-button {
color: green;
}
</style>
<style module>
/* CSS Modules */
.button {
color: blue;
}
</style>
<template>
<button :class="[$style.button, 'global-button']">點我</button>
</template>
以上就是在 Vue 中使用 CSS Modules 的基本方法。