useCssModule
When cssModule is enabled on Vue, you can use this API to fetch the className processed by vue-loader.
- HelloWorld.vue
// template
<div :class="$style.hello">text</div>
// script
export default {
setup() {
const $style = useCssModule()
console.log($style.hello); // "HelloWorld_hello_1ae9G"}}// style
<style module>
.hello {
color: red;
}
</style>
Copy the code
Vue CSS Modules document reference
The source code parsing
Gets the type.__cssmodules.$style object under the current component instance.
Tip: __cssModules are injected by vue-loader
function useCssModule(name = '$style') { if (! __GLOBAL__) { const instance = getCurrentInstance()! const modules = instance.type.__cssModules const mod = modules[name] if (! mod) { return EMPTY_OBJ } return mod } else { return EMPTY_OBJ } }Copy the code
Simple encapsulation example
import { useCssModule, ref, watchEffect } from 'vue'
function useClassnames(namesGetter) {
const $styles = useCssModule()
const classnames = ref([])
watchEffect(function() {
classnames.value = getClassnames()
})
function getClassnames() {
const names = namesGetter()
if (Array.isArray(names)) {
return names.filter(i => !!i).map(it => $styles[it])
} else {
const result = []
for (const key in names) {
names[key] && classNames.push($styles[key])
}
return result
}
}
return classnames
}
// 使用
const rootStyle = useClassnames(() => ({
hello: true,
active: props.active
}))
Copy the code
Copy the code
useCssVars
Add CSS variables to the style of the root EL of the Vue component.
/ / usage
// template
<div class="text-color">1</div>
// script
function useTheme() {
const theme = reactive({
textColor: '#b53f6b'
})
const getTheme = (useProxy) = > {
const { active } = useProxy
return active ? theme : {}
}
useCssVars(getTheme)
}
export default {
setup() {
useTheme()
const active = ref(true)
return { active }
}
}
// style
.text-color {
color: var(--textColor);
}
Copy the code
UseCssVars implementation source code
useContext
Gets the context, the second argument to the setup method in the current component
function useHeaderSlot() {
const { slots } = useContext()
return slots && slots.header
}
export default {
setup() {
const headerSlot = useHeaderSlot()
}
}
Copy the code
useSSRContext
expand
The Compositon API no longer exists this. So getting the method that the plug-in adds to the global is a hassle. But it can be retrieved from the proxy object of the component instance.
// main.js
const app = createApp(App)
app.config.globalProperties.foo = 'bar'
app.mount('#app')
// useRenderContext,js
function useRenderContext(){
const i = getCurrentInstance()!
return i.proxy
}
setup() {
const { foo } = useRenderContext()
foo // bar
}
Copy the code