Skip to content

Instantly share code, notes, and snippets.

@mgaffigan
Created November 22, 2019 03:56
Show Gist options
  • Save mgaffigan/e86754fedbf3c71bbfb36276ba42f1a4 to your computer and use it in GitHub Desktop.
Save mgaffigan/e86754fedbf3c71bbfb36276ba42f1a4 to your computer and use it in GitHub Desktop.
Example of using Vue to have a dynamic set of combo boxes
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello, world!</title>
</head>
<body>
<section class="regionapp">
<header class="header">
<h1>regions</h1>
<select class="new-region" v-model="newRegion" @keyup.enter="addRegion">
<option value="EMEA">EMEA</option>
<option value="North America">North America</option>
<option value="Asia">Asia</option>
</select>
<button @click="addRegion">add</button>
</header>
<div v-for="region in regions" :key="region.id">
<h2>{{ region.title }}</h2>
<div>
<label>Sales: </label>
<input type="number" v-model="region.sales" />
</div>
<div>
<label>Employees: </label>
<input type="number" v-model="region.employees" />
</div>
<button @click="removeRegion(region)">remove</button>
</div>
<p>{{ stats.regionCount }} regions, {{ stats.totalSales }} total sales, {{ stats.totalEmployees }} employees</p>
</section>
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js" crossorigin="anonymous"></script>
<script>
var app = new Vue({
data: {
regions: [],
newRegion: '',
},
computed: {
stats: function () {
const sumOf = function (arr, selector) { return arr.map(selector).reduce((a, b) => a + b, 0); };
return {
regionCount: this.regions.length,
totalSales: sumOf(this.regions, r => +r.sales),
totalEmployees: sumOf(this.regions, r => +r.employees),
};
}
},
// methods that implement data logic.
// note there's no DOM manipulation here at all.
methods: {
addRegion: function () {
var value = this.newRegion && this.newRegion.trim();
if (!value) {
return;
}
this.regions.push({
title: value,
id: this.regions.length,
sales: 0,
employees: 0
});
this.newRegion = ''
},
removeRegion: function (region) {
this.regions.splice(this.regions.indexOf(region), 1)
},
},
})
// mount
app.$mount('.regionapp');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment