Newer
Older
vue-demo / vue-client / static / js / student.js
/* global Vue, axios */

var studentListApi = '//localhost:8080/api/students';
var studentApi = ({id}) => `//localhost:8080/api/students/${id}`;

const app = Vue.createApp({

	// bind dataStore variables to models
	computed: Vuex.mapState({
		student: 'selectedStudent',
		editing: 'editMode',
	}),

	methods: {

		save() {

			if (this.editing) {

				// send PUT request to service to update student
				axios.put(studentApi({id: this.student.id}), this.student)
					.then(() => {
						window.location = 'list.html';
					})
					.catch(error => {
						console.error(error);
						alert("An error occurred - check the console for details.");
					});

			} else {

				// send POST request to service to create student
				axios.post(studentListApi, this.student)
					.then(() => {
						window.location = 'list.html';
					})
					.catch(error => {
						console.error(error);
						alert("An error occurred - check the console for details.");
					});
			}

		},

		edit() {
			dataStore.commit('edit', this.student);
			window.location = 'add.html';
		},

		remove() {
			// send DELETE request to service to delete student
			axios.delete(studentApi({id: this.student.id}))
				.then(() => {
					window.location = 'list.html';
				})
				.catch(error => {
					console.error(error);
					alert("An error occurred - check the console for details.");
				});
		}
	}
});

// import data store
import { dataStore } from './data-store.js'
app.use(dataStore);

// import page header component
import { PageHeader } from './page-header.js';
app.component('pageheader', PageHeader);

app.mount('#content');