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 121<br />

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

2 ...<br />

3 methods: {<br />

4 ...<br />

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

6 this.$http.post('/api/stories/', story).then(function(response) {<br />

7 Vue.set(story, 'id', response.data.id);<br />

8 story.editing = false;<br />

9 });<br />

10 },<br />

11 }<br />

12 ...<br />

13 })<br />

I use Vue.set(story, 'id', response.data.id) instead of story.id = response.data.id because<br />

inside our table we display the id of each story. Since the new story had no id when pushed<br />

to the stories array the DOM won’t be updated when the id changes, so we will not be able to see<br />

the new id.<br />

Tip<br />

When you are adding a new property that wasn’t present when the data was observed,<br />

Vue.js cannot detect the property’s addition. So, if you need to add or remove properties at<br />

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

10.4 JavaScript File<br />

As you may have noticed, our code is becoming big, and as our project grows, it will be hard to<br />

maintain. For starters, we’ll separate the JavaScript code from the HTML. I’ll create a file called<br />

app.js and I’ll save it under js directory.<br />

All the JavaScript code should live inside that file from now on. To include the newly created script<br />

to any HTML page you simply have to add this tag<br />

1 <br />

and you are ready to go!

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

Saved successfully!

Ooh no, something went wrong!