1. style 中使用v-bind
不支持响应式渲染
1 <template> 2 <p class="msg">Hello World!</p> 3 </template> 4 5 <script lang="ts"> 6 import { defineComponent, ref } from 'vue' 7 8 export default defineComponent({ 9 setup () { 10 const fontColor = ref<string>('#ff0000') 11 12 return { 13 fontColor, 14 } 15 } 16 }) 17 </script> 18 19 <style scoped> 20 .msg { 21 color: v-bind(fontColor); 22 } 23 </style>
2. :style 动态修改内联样式
1 <template> 2 <p 3 :style="[style1, style2]" 4 > 5 Hello World! 6 </p> 7 </template> 8 9 <script lang="ts"> 10 import { defineComponent } from 'vue' 11 12 export default defineComponent({ 13 setup () { 14 const style1 = { 15 fontSize: '13px', 16 'line-height': 2, 17 } 18 const style2 = { 19 color: '#ff0000', 20 textAlign: 'center', 21 } 22 23 return { 24 style1, 25 style2, 26 } 27 } 28 }) 29 </script>
3. 动态绑定CSS
1 <template> 2 <p 3 :class="[ 4 { activeClass1: isActive }, 5 { activeClass2: !isActive } 6 ]" 7 > 8 Hello World! 9 </p> 10 </template> 11 <script lang="ts"> 12 import { defineComponent } from 'vue' 13 14 export default defineComponent({ 15 setup () { 16 const activeClass = 'active-class' 17 const activeClass1 = 'active-class1' 18 const activeClass2 = 'active-class2' 19 const isActive = true 20 21 return { 22 activeClass, 23 activeClass1, 24 activeClass2, 25 isActive, 26 } 27 } 28 }) 29 </script>
4. 防止CSS样式全局污染
scoped
1 <style scoped> 2 .msg { 3 width: 100%; 4 } 5 .msg p { 6 color: #333; 7 font-size: 14px; 8 } 9 </style>
style module
1 <template> 2 <p :class="$style.msg">Hello World!</p> 3 </template> 4 5 <style module> 6 .msg { 7 color: #ff0000; 8 } 9 </style>
自定义module名
1 <template> 2 <p :class="classes.msg">Hello World!</p> 3 </template> 4 5 <style module="classes"> 6 .msg { 7 color: #ff0000; 8 } 9 </style>
useCssModule
1 <template> 2 <div v-html="content"></div> 3 </template> 4 5 <script lang="ts"> 6 import { defineComponent, useCssModule } from 'vue' 7 8 export default defineComponent({ 9 setup () { 10 // 获取样式 11 const style = useCssModule() 12 13 // 编写模板内容 14 const content = `<p class="${style.msg}"> 15 <span class="${style.text}">Hello World! —— from v-html</span> 16 </p>` 17 18 return { 19 content, 20 } 21 } 22 }) 23 </script> 24 25 <style module> 26 .msg { 27 color: #ff0000; 28 } 29 .text { 30 font-size: 14px; 31 } 32 </style>
来自于: https://vue3.chengpeiquan.com/component.html#usecssmodule-new