CSS Only Dropdown Menu
As someone who basically gets by when it comes to writing Javascript, I tend to look at things from a “I bet I could do this with CSS” st...
CSS SCSS Mobile UX UI/UX frontendHave you found yourself getting lost in large Vue components that have multiple features? The Composition API is a new optional syntax in Vue 3 that provides developers a new way to create components and organize them by feature instead of operation.
The Composition API is available to try out with Vue 2 as a plugin.
taken from Vue’s request for comment.
<template>
<button @click="increment">
Count is: , double is:
</button>
</template>
<script>
import { reactive, computed } from 'vue'
export default {
setup() {
const state = reactive({
count: 0,
double: computed(() => state.count * 2)
})
function increment() {
state.count++
}
return {
state,
increment
}
}
}
</script>
The setup function is where you put your data and functions for your feature. You could also move your feature code into its own function outside of the setup or its own javascript file and then would have to declare the code in the setup function and return it to use.
There are two ways to deal with state and reactivity in the setup function, refs and reactive. Using one over the other is a matter of preference and coding style. They both allow Vue to keep track of your state.
Knowing when to use refs and reactive can be confusing and best practices are still being developed
<template>
<button @click="increment">
Count is: {{ count.value }}, double is: {{ count.value * 2 }}
</button>
</template>
<script>
import { ref, watch } from 'vue'
let count = ref(0)
function increment() {
count.value++
}
const renderContext = {
count,
increment
}
watch(() => {
renderTemplate(
`<button @click="increment">8</button>`,
renderContext
)
})
</script>
Refs in the setup function work differently then refs in the rest of Vue. In the setup function when using a ref you declare the variable and set the initial value using ref()
.
let todo = ref('')
Working with your data in the template section of the component you need to reference the data with the name of the ref and add .value at the end
<h1> {{ todo.value }} </h1>
Reactive takes an object and returns a reactive object
setup() {
Const todos = reactive({
item: ''
}) }
return {...toRefs(todos)}
Used with refs or reactive when you have state that depends on other state.
let firstTodo = computed(( ) => {return todo[0] } )
The second optional argument in the setup function that allows you to call methods like emit that are not available in the setup function.
If you want to start experimenting with the composition API you can use it as a plugin with Vue 2.
Vue Mastery’s Composition API Cheat Sheet