code.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. // Or use axios directly instead of this.$http.
  2. Vue.prototype.$http = axios;
  3. class Errors {
  4. constructor() {
  5. this.clear();
  6. }
  7. any() {
  8. return Object.keys(this.errors).length != 0;
  9. }
  10. clear(name) {
  11. console.log("clearing", name);
  12. this.errors = {};
  13. }
  14. get(field) {
  15. if (this.errors[field]) {
  16. return this.errors[field];
  17. }
  18. }
  19. has(field) {
  20. return this.errors.hasOwnProperty(field);
  21. }
  22. record(errors) {
  23. this.errors = errors;
  24. }
  25. }
  26. Vue.component('list', {
  27. methods: {
  28. },
  29. data() {
  30. return {};
  31. },
  32. template: '#list',
  33. props: {
  34. 'projects': {
  35. default: () => { return {}; },
  36. // type: Object,
  37. }
  38. },
  39. });
  40. class Form {
  41. constructor(data) {
  42. this.keys = Object.keys(data);
  43. this.errors = new Errors();
  44. for (const field in data) {
  45. this[field] = data[field];
  46. }
  47. }
  48. reset() {
  49. for (const field of this.keys) {
  50. this[field] = null;
  51. }
  52. }
  53. submit() {
  54. }
  55. }
  56. const app = new Vue({
  57. el: '#root',
  58. data: {
  59. form: new Form({
  60. name: '',
  61. description: '',
  62. }),
  63. projects: [],
  64. },
  65. beforeMount() {
  66. this.updateProjects();
  67. },
  68. methods: {
  69. updateProjects() {
  70. this.$http.get('index.php/projects')
  71. .then(this.onGotProjects);
  72. },
  73. onGotProjects(e) {
  74. this.projects = e.data;
  75. },
  76. /**
  77. *
  78. * @param {Event} e
  79. */
  80. onSubmit(e) {
  81. // or use @submit.prevent at the HTML call point
  82. // e.preventDefault();
  83. this.$http.post('index.php/projects', this.$data.form)
  84. .then(this.onSuccess)
  85. .catch(error => {
  86. this.form.errors.record({'name': error.response.data});
  87. });
  88. },
  89. onSuccess() {
  90. this.updateProjects();
  91. alert('Success');
  92. this.form.reset();
  93. }
  94. }
  95. });