-
-
Save jonasbn/ac143b490f38c887a0095b5dec7548d7 to your computer and use it in GitHub Desktop.
Mojolicious - Vue.js Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use Mojolicious::Lite -signatures; | |
get '/' => sub ($c) { | |
$c->render(template => 'index'); | |
}; | |
get '/api/:region' => sub ($c) { | |
my %regions = ( | |
north => { | |
countries => [ | |
'Antigua and Barbuda', 'Bahamas', | |
'Barbados', 'Belize', | |
'Canada', 'Costa Rica', | |
'Cuba', 'Dominica', | |
'Dominican Republic', 'El Salvador', | |
'Grenada', 'Guatemala', | |
'Haiti', 'Honduras', | |
'Jamaica', 'Mexico', | |
'Nicaragua', 'Panama', | |
'Saint Kitts and Nevis', 'Saint Lucia', | |
'Saint Vincent and the Grenadines', 'Trinidad and Tobago', | |
'United States', | |
], | |
region => 'North America', | |
}, | |
south => { | |
countries => [ | |
'Argentina', 'Bolivia', 'Brazil', 'Chile', | |
'Colombia', 'Ecuador', 'Guyana', 'Paraguay', | |
'Peru', 'Suriname', 'Uruguay', 'Venezuela', | |
], | |
region => 'South America', | |
}, | |
); | |
my $region = $regions{$c->param('region')} || {}; | |
$c->render(json => $region); | |
}; | |
app->start; | |
__DATA__ | |
@@ index.html.ep | |
% layout 'default'; | |
% title 'Mojolicious-Vue.js Example'; | |
<div id="app"> | |
<h1>Countries in {{ area.region }}</h1> | |
<table> | |
<tr v-for="country in area.countries"><td>{{ country }}</td></tr> | |
</table> | |
<button v-on:click="showRegion()">Show countries in {{oppositeRegion}}</button> | |
</div> | |
%= javascript 'https://unpkg.com/vue/dist/vue.min.js' | |
%= javascript 'https://unpkg.com/axios/dist/axios.min.js' | |
%= javascript begin | |
var app = new Vue({ | |
el: '#app', | |
created: function() { | |
this.getRegion('south'); | |
this.oppositeRegion = 'north' | |
}, | |
data: { area: {}, oppositeRegion: '' }, | |
methods: { | |
getRegion: function(area) { | |
var self = this; | |
axios.get('/api/' + area).then( | |
function(response) { | |
self.area = response.data; | |
} | |
); | |
}, | |
showRegion: function() { | |
if (this.oppositeRegion === 'south') { | |
this.getRegion('south'); | |
this.oppositeRegion = 'north'; | |
} else { | |
this.getRegion('north'); | |
this.oppositeRegion = 'south'; | |
} | |
} | |
} | |
}); | |
% end | |
@@ layouts/default.html.ep | |
<!DOCTYPE html> | |
<html> | |
<head><title><%= title %></title></head> | |
<body><%= content %></body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment