08.02.2017 Views

vuejs

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Integrating vue-resource 112<br />

19 <br />

20 {{story.upvotes}}<br />

21 <br />

22 <br />

23 <br />

24 <br />

25 Upvote<br />

26 <br />

27 <br />

28 Edit<br />

29 <br />

30 <br />

31 Delete<br />

32 <br />

33 <br />

34 <br />

1 Vue.component('story',{<br />

2 ...<br />

3 methods: {<br />

4 ...<br />

5 editStory: function(story){<br />

6 story.editing=true;<br />

7 },<br />

8 }<br />

9 ...<br />

10 })<br />

This is our updated table with two new inputs and a button. We use the editStory function to set<br />

story.editing to true , so v-if will bring up the inputs to edit the story and hide the ‘Upvote’ and<br />

‘Delete’ buttons. But this approach won’t work. It seems that the DOM isn’t updating after setting<br />

story.editing to true. Why this may be happening?<br />

It turns out, according to this post from Vue.js blog³ that when you are adding a new property<br />

that wasn’t present when the data was observed the DOM won’t update. The best practice is to<br />

always declare properties that need to be reactive upfront. In cases where you absolutely need to<br />

add or delete properties at runtime, use the global Vue.set or Vue.delete methods.<br />

For this reason, we have to initialize the story.editing attribute to false on each story, right after<br />

receiving the stories from the server.<br />

To do this, we are going to use javascript’s .map() method within the success callback of the GET<br />

request.<br />

³http://<strong>vuejs</strong>.org/2016/02/06/common-gotchas/

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!