Setting a New Property in Vue 3 on a Data Object

Published Jun 19, 2024
Updated Jun 19, 2024
By Simon
Table of contents

If you came from the to-do app example article, you would have learnt how to use set() to mark tasks completed by setting a new property to the data object. Or you may have skipped that and come straight here.

In this article, we will look at how we don't need to use set() in Vue3. We can directly add new properties to our data objects using dot notation property accessor, and the reactivity of your app won't break and the new property and value will be reflected in the front-end code instantly.

In Vue 2 you had to use the set() method to add a new property to a data object.

Say your data object was like this. 

tasks: [
 {index: 'eat sushi 🍣',todo: 'eat sush 🍣'},
 {index: 'study Vue.js', todo: 'study 💚 Vue.js'}
],

Then, in your template code, you would need to use the set method on the click event as shown below.

<button v-on:click="$set(item, 'edit', 'edit')" class="button-round">Edit</button>
<!-- Or negated the value of edit -->
<button v-on:click="$set(item, 'edit', !item.edit)" class="button-round">Edit</button>

Note: This would probably be in a v-for loop, so the item would be the item associated with the record. See using v-for in Vue.js https://vuejs.org/guide/essentials/list.html

 

Don't understand how the ! works in JavaScript. Learn about how to negate a value in JavaScript with a basic example.

The above click event would have resulted in.

-  {index: 'eat sushi 🍣',todo: 'eat sush 🍣'},
+  {index: 'eat sushi 🍣',todo: 'eat sush 🍣', edit: true},

See how we now have the new property edit with the value true on one of the items.

However, in Vue 3 you can just do this. 

<button v-on:click="item.edit='true'" class="button-round">Edit</button>
<!-- Or negated the value of edit -->
<button v-on:click="item.edit=!item.edit" class="button-round">Edit</button>

We can use the dot notation property accessor to set new properties and it works.

Note: In a real world situation, you will possibly want to set the data object up with all the properties and set a default value; I am sure in TypeScript, this would almost be the case. If you had done this, then set was never needed. I guess, though, having the flexibility to add a new property could be useful in some circumstances; I will let you know when I come across this case.

Well, that's it. Sorry if it's a let-down but I that's the elegance of Vue.js. 

Thanks for reading; I write a weekly newsletter on front-end design and development, drawing from my twenty years experience in full stack development.  It's a work in progress and a journey in itself. Be sure to sign up below or in that pesky pop up over there.

Until next time, Carpe diem.