VueJS 2.x and 3.x snippets
...because sometimes useful pieces of code have to be written down and re-used!
Conditionally adding attribute
It's good to know how to add attribute to element if some conditions are met. For example I use it when I show links in loop and want to add target="_blank"
to a
element ONLY if I set newTab
to true. In Vue3 it would look like: <a href="item.url" :target="item.newTab ? '_blank': null" v-text="item.label" />
Conditional rendering of attributes changed in Vue 3. To omit an attribute use null
or undefined
.
Vue 2.x
html
<div :attr="false">
<!-- Result: --> <div>
html
<div :attr="null">
<!-- Result: --> <div>
Vue 3.x
html
<div :attr="false">
<!-- Result: --> <div attr="false">
html
<div :attr="null">
<!-- Result: --> <div>