(And, more importantly... how to avoid them)
ue.js
Lead Instructor @ Vue School
Full Stack developer (10 + years)
Husband and Father
presentation Icons from fontawesome.com
<li
v-for="(item, index) in items"
:key="index"
>...</li>
What's wrong with this? 🤔
<li
v-for="(item, index) in items"
:key="index"
>...</li>
What's wrong with this? 🤔
Bug Manifests Under 2 Conditions
It's tricky!
Let's look at an example!
It's not just for loops!
Let's look at an example!
const cookiesAccepted = computed(()=>
localStorage.getItem("cookiesAccepted")
)
What's wrong with this? 🤔
const cookiesAccepted = computed(()=>
localStorage.getItem("cookiesAccepted")
)
What's wrong with this? 🤔
const cookiesAccepted = computed(()=>
localStorage.getItem("cookiesAccepted")
) // 0
localStorage.setItem("cookiesAccepted", 1)
cookiesAccepted.value // 0
Changing the value of local storage doesn't update the value of the computed prop.
const accepted = 0;
const cookiesAccepted = computed(()=> accepted)
This is more obvious
Often see this with browser API's:
And, of course, usually these hide in more complex computed props
(nothing as obvious as our simple example)
What's the solution?
🤔
VueUse
VueUse
handy reactive wrapper around browser APIs
Let's look at an example!
let posts = reactive([
'Post 1',
'Post 2'
]);
function loadMore(){
// fetch more posts, etc
posts = newPosts;
}
What's wrong
with this? 🤔
let posts = reactive([
'Post 1',
'Post 2'
]);
function loadMore(){
// fetch more posts, etc
posts = newPosts;
}
What's wrong
with this? 🤔
👈 replacing reactive
kills reactivity
Let's look at some examples!
Moral of the story:
just use ref() everywhere!
I'm not the only one,
it's the recommendation of the official Vue.js docs
I'm not the only one,
it's the recommendation of the official Vue.js docs
Oh and one more reason to use ref() everywhere
default watcher depth is different between ref() and reactive()
Let's see an example of that
<script setup lang="ts">
defineProps<{
modelValue: string;
}>();
</script>
<template>
<input id="username" v-model="modelValue" />
</template>
What's wrong with this? 🤔
<script setup lang="ts">
defineProps<{
modelValue: string;
}>();
</script>
<template>
<input id="username" v-model="modelValue" />
</template>
What's wrong with this? 🤔
Mutating a prop
Let's look at some examples!
🔥 Free
https://vueschool.io/courses/common-vue-js-mistakes-and-how-to-avoid-them
👈
👈
👈
👈
But before I go!
vue.school/masterclass
Not just crappy multiple choice questions
👉 you gotta code to pass
83% say the exam is moderate to difficult
74% say it actually helped improve their Vue.js skills
danielkelly_io
I'll tweet out the slides and the codebase after this
Go code awesome things!
(with Vue 😉)