Frontend Engineer
Content creator at
The Composable Pattern will help you build (more) Extensible, Adaptable, Controllable and Trustful Vue.js applications.
A function that leverages Vue's Composition API to encapsulate and reuse stateful logic.
import { ref } from "vue"
// We always export a main function
export function useAlert() {
// Stateless: every instance holds its own state
const isVisible = ref(true)
// We craft our custom logic
const toggleVisibility = () => isVisible.value = !isVisible.value
// We expose what we want to consume
return {
isVisible,
toggleVisibility
}
}
The Composable Pattern will help you build (more) Extensible, Adaptable, Controllable and Trustful Vue.js applications.
import { ref } from "vue"
export function useAlert() {
// Stateless
const isVisible = ref(true)
...
}
import { ref } from "vue"
// Stateful
const isVisible = ref(true)
export function useAlert() {
...
}
import { ref } from "vue"
const isVisible = ref(true)
// We expect an options object
export function useAlert(options) {
// We specify a default
const { isDanger = true, awaitResult = true } = options
...
}
import { ref } from "vue"
import { useLocalStorage } from '@/composables'
const isVisible = ref(true)
export function useAlert() {
const { save, check, remove } = useLocalStorage({ key: 'my-app'})
...
}
UseEvent
UseCalendar
UsePayment
UseDarkMode
UseIntersectionObserver
UseFilter
UseUnique
UseReduce
export function useAlert() {
const isVisible = ref(true)
const toggleVisibility = () => isVisible.value = !isVisible.value
return {
toggleVisibility
}
}
import { ref, readonly } from "vue"
export function useAlert() {
const isVisible = ref(true)
const toggleVisibility = () => isVisible.value = !isVisible.value
return {
isVisible: readonly(isVisible),
toggleVisibility
}
}
import { useAlert } from '@/composables'
const { isVisible: isNotHidden, toggleVisibility } = useAlert()
export function useAlert() {
...
return {
isNotHidden:isVisible,
toggleVisibility
}
}
import { useAlert } from '.'
describe('useAlert', () => {
it('has the initial state as visible', () => {
const { isVisible } = useAlert()
expect(isVisible.value).toBe(true)
})
it('toggleVisibility() mutates the state', () => {
const { isVisible, toggleVisibility } = useAlert()
toggleVisibility()
expect(isVisible.value).toBe(false)
})
})
(See you in the workshop 🔥)