code.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. },
  33. template: `
  34. <table class="table">
  35. <caption>List of projects</caption>
  36. <thead>
  37. <tr>
  38. <th>Name</th>
  39. <th>Description</th>
  40. </tr>
  41. </thead>
  42. <tbody>
  43. <!-- props are directly available by name -->
  44. <tr v-for="project in projects">
  45. <td>{{ project.name }}</td>
  46. <td>{{ project.description }}</td>
  47. </tr>
  48. </tbody>
  49. </table>
  50. `,
  51. props: {
  52. 'projects': {
  53. default: () => { return {}; },
  54. // type: Object,
  55. }
  56. },
  57. });
  58. const app = new Vue({
  59. el: '#root',
  60. data: {
  61. name: '',
  62. description: '',
  63. errors: new Errors(),
  64. projects: [],
  65. },
  66. beforeMount() {
  67. this.$http.get('index.php/projects')
  68. .then(this.onGotProjects);
  69. },
  70. methods: {
  71. onGotProjects(e) {
  72. this.projects = e.data;
  73. },
  74. /**
  75. *
  76. * @param {Event} e
  77. */
  78. onSubmit(e) {
  79. // or use @submit.prevent at the HTML call point
  80. // e.preventDefault();
  81. this.$http.post('index.php/projects', this.$data)
  82. .then(this.onSuccess)
  83. .catch(error => this.errors.record({'name': error.response.data}));
  84. },
  85. onSuccess() {
  86. alert('Success');
  87. }
  88. }
  89. });