v0.4 - Methods and Data Fetching
Methods
Methods are how we define functions that interact with our application's state. This might be a function called on a button click that toggles a setting or submits data to a server.
Let go in and set up our first method. It is simply going to toggle the order of our sorting Z-A rather than A-Z.
Lets start by creating the button. Milligram.css has already made the classes needed for this so its real easy to do. We are going to create two states for this button, the A-Z state and the Z-A state. The button will show the current ordering direction and will toggle it to the other direction on click.
index.html
<input v-model="search"
type="text"
style="width:200px"
placeholder="Search..">
<div class="button"
v-on:click="toggleSort()">
{{sort_btn_text}} ↓
</div>
<div v-for="f in filtered_food">
{{f.icon}} {{f.name}}
</div>
To break this down a bit, lets start with the v-on:click directive. Any click on the button we have made will now call the toggleSort() function. v-on can be used to handle many different types of events. Including common ones like enter, up and submit (on forms).
TIP
v-on:click="toggleSort" can be shorthanded to just @click="toggleSort"
We have put the variable sort_btn_text inside of the button, we will make this a computed variable that updates based on whichever direction we are sorting in.
In our app we are going to need to do a few things. First, we need to store which direction we are sorting in. We are going to store it as sort_modifier. This will be either 1 (no modification) or -1 (flipped). We will multiply the return in the sort function by this modifier to get reverse order.
We will need to define our method toggleSort. Similarly to computed variables we need to create a new object on our instance, keyed to methods. We can then define toggleSort in there, a simple function that just multiplies the existing value by -1.
app.js
const app = new Vue({
el: '#app',
computed: {
filtered_food() {
return this.food
.filter(f => f.name.indexOf(this.search) !== -1)
.sort((a, b) => {
if (a.name > b.name) return this.sort_modifier;
if (a.name < b.name) return this.sort_modifier * -1;
return 0;
})
},
sort_btn_text() {
return this.sort_modifier>0?'A-Z':'Z-A'
}
},
data: {
search: '',
message: 'Good morning, have a 🥐',
food: [...],
sort_modifier: 1
},
methods: {
toggleSort() {
this.sort_modifier = this.sort_modifier * -1;
}
}
})
Data fetching
Lets fetch some more interesting data to play with. I have put a list of concerts happening in Toronto (scraped from Facebook) into a gist on github. We can use the fetch API (this is not Vue specific, it is a newer API available on some modern browsers) to grab this data from the gist and put it into our application. In a real application this data would likely be pulled in from your own API.
api.js
methods: {
toggleSort() {...},
getConcerts() {
fetch('https://gist.githubusercontent.com/nchudleigh/92637a91938b16e105105de3ee91a569/raw/bbb5b1d549847e74afca77c2cfa3b514585678ad/events.json')
.then(r => {
return r.json();
})
.then(r => {
console.table(r);
})
}
}
Hop into your console and type app.getConcerts(). You will see a table of the events we have just pulled.

Lets break down what is going on here. Fetch is making a GET request to the gist I have set up. Fetch returns a Promise, which exists in Javascript to handle things that will take an unknown amount of time (such as a request). With Promises you have to use then to register which function will handle the response. Fetch also implements a .json() function on its responses. This returns a Promise (whoa), which when resolved gives us the response, converted to json.
In our second then handler we are taking our converted response and logging it to the console in table format. This will allow us to see a bit more information without having to poke around too much.
FUN FACT
I learned about console.table while writing this course (Oh the wasted hours!). It is incredibly useful, and is really smart about how it handles your data before displaying. You can also sort the columns by clicking their headers.
We are going to save these concerts to our app data at the key concerts.
So we will just replace the console.table call with this.concerts = r. We also want to initialize the data key with an empty array.
app.js
data: {
search: '',
message: 'Good morning, have a 🥐',
food: [...],
concerts: [],
sort_modifier: -1
},
methods: {
toggleSort() {...},
getConcerts() {
fetch('https://gist.githubusercontent.com/nchudleigh/92637a91938b16e105105de3ee91a569/raw/bbb5b1d549847e74afca77c2cfa3b514585678ad/events.json')
.then(r => r.json())
.then(r => {
this.concerts = r;
})
}
}
You may have noticed that I also shortened the first .then handler to one line. This can be done because arrow functions, without curly braces {} return whatever statement you give them. So instead of typing out the explicit return we can just use r.json()
Now we have some really interesting data to play around with. Lets, update our filtered_food computed variable to be filtered_concerts and use this.concerts instead of this.food We can also delete our food variable now.
app.js
computed: {
filtered_concerts() {
return this.concerts
.filter(f => f.name.indexOf(this.search) !== -1)
.sort((a,b) => {
if (a.name > b.name) return 1 * this.sort_modifier;
if (a.name < b.name) return -1 * this.sort_modifier;
return 0;
})
},
sort_btn_text() {...}
},
We will also need to update the v-for we wrote earlier to use filtered_concerts instead of filtered_food. We can also remove the f.icon since you template variable since our concerts don't have icons.
index.html
<div class="button"
@click="toggleSort()">
{{sort_btn_text}} ↓
</div>
<div v-for="f in filtered_concerts">
{{f.name}}
</div>
Lastly, we are going to want to make sure that these concerts get pulled every time we refresh the page. In Vue we can do this by using the created lifecycle hooks. This is a special function that gets run after the app is created. We are going to call our getConcerts method in here.
app.js
data: {...},
created() {
this.getConcerts();
},
methods: {...}
We can now refresh our app and see all of our concerts listed by name, try out the search and sorting! It will all still work the same as before.