Vue Coding Guidelines
Put default values for array/objects into a function
❌
props: {
blok: {
type: Object,
default: () => {}
}
},
✅
props: {
blok: {
type: Object,
default: () => ({}) // <-- use this
}
},
Default value for Array/Object
document.getElementById
and other js dom queries
Avoid using ❌
<template>
<div>
<div id="my-dom-element">Hello world</div>
</div>
</template>
<script>
export default {
mounted() {
document.getElementById('my-dom-element').setAttribute('disabled', true)
}
}
</script>
❌
<template>
<div>
<div id="my-dom-element">Hello world</div>
</div>
</template>
<script>
export default {
mounted() {
this.$nextTick(function (){
document.getElementById('my-dom-element').setAttribute('disabled', true)
})
}
}
</script>
🤔 Use the #ref parameter. But not best option
<template>
<div>
<div id="my-dom-element" ref="my-dom-element">Hello world</div>
</div>
</template>
<script>
export default {
mounted() {
this.$refs.myDomElement.setAttribute('disabled')
}
}
</script>
✅ Use template Syntax Attributes
<template>
<div>
<div id="my-dom-element" :disabled="IsdisabledDomElement">Hello world</div>
</div>
</template>
<script>
export default {
data() {
isDisabledDomElement: false
}
mounted() {
this.isDisabledDomElement = true
}
}
</script>
Read more (https://vuejs.org/v2/api/#mounted)[https://vuejs.org/v2/api/#mounted]
Avoid renaming components with name prop
❌
components/bloks/BlokText.vue
<template>
<div>
<div>{{ title }}</div>
</div>
</template>
<script>
export default {
name: 'MyTextBlok'
}
</script>
❌🤔
components/bloks/BlokText.vue
<template>
<div>
<div>{{ title }}</div>
</div>
</template>
<script>
export default {
name: 'BlokText'
}
</script>
✅
components/bloks/BlokText.vue
<template>
<div>
<div>{{ title }}</div>
</div>
</template>
<script>
export default {
}
</script>
Nullish coalescing
❌
const defaultTime = 2;
const animationTime = settings.animationTime || defaultTime;
From this blog post
This code might work in general, but there is a subtle bug. The Boolean false, empty strings (""), NaN, >and the number 0 are all falsy. In this example, a user might not want any animations at all. But if he >or she sets the time to 0, this code will ignore it and erroneously use the default value of 2.
More explicit:
const defaultTime = 2;
const animationTime =
typeof settings.animationTime === "number"
? settings.animationTime
: defaultTime;
✅
const defaultTime = 2;
const animationTime = settings.animationTime ?? defaultTime;