I had been using Nuxtjs 3 for sometime, and I’ve started to like it more. I started using Nuxtjs 3 ever since Nextjs got messier with Server first move.
After working with Nuxt 3, I also found myself having fun with Nuxt UI 3 as well. The simplicity and structured approach of Nuxt and Nuxt UI are pretty good.
I like the composition api of Vue3, which is a very good feature.
Composition API
Composntion API Provides reactivity for vue in a very intuitive way.
Some of the api’s are:
State
ref
: good for storing primitive type values
const name = ref("John");
reactive
: good for storing arrays and objects
const person = reactive({
name: "John",
age: 30,
});
computed
: reacts or computes values from a ref or a reactive object
const fullName = computed(() => `${person.name} ${person.lastName}`);
readonly
: set a ref or reactive object as readonly
const name = readonly("John");
Watcher
watch
: watches for changes in a ref or reactive object
watch(name, (newValue, oldValue) => {
// executes when name changes
console.log(newValue, oldValue);
});
watchEffect
: watches for changes in a ref or reactive object
watchEffect(() => {
// executes when name changes
console.log(name.value);
});
Dependancy Injection
provide
: provides a ref or reactive object which can be used by any child components
provide("name", "John");
inject
: used to read a provided value
const name = inject("name");
Composables
Composables are basically reusable functions which can be called from any component or even other composables. ( It feels like composition api in react, without extra steps )
We can define a composable like this
const useCounter = () => {
const count = ref(0);
const increment = () => {
count.value++;
};
return { count, increment };
};
And then we can use it like this
const { count, increment } = useCounter();
Some of the practices I follow with these composition api are:
- Using
.value
to access ref value outside templates - Using
ref
for primitive types andreactive
for objects - Using
computed
whenever possible thanwatch
orwatchEffect
- Using
provide
andinject
for simple data sharing and composables for data with crud like operations.