app.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. var baseURL = 'https://vue-demo.firebaseIO.com/'
  2. var emailRE = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  3. /**
  4. * Setup firebase sync
  5. */
  6. var Users = new Firebase(baseURL + 'users')
  7. Users.on('child_added', function (snapshot) {
  8. var item = snapshot.val()
  9. item.id = snapshot.key()
  10. app.users.push(item)
  11. })
  12. Users.on('child_removed', function (snapshot) {
  13. var id = snapshot.key()
  14. app.users.some(function (user) {
  15. if (user.id === id) {
  16. app.users.$remove(user)
  17. return true
  18. }
  19. })
  20. })
  21. /**
  22. * Create Vue app
  23. */
  24. var app = new Vue({
  25. // element to mount to
  26. el: '#app',
  27. // initial data
  28. data: {
  29. users: [],
  30. newUser: {
  31. name: '',
  32. email: ''
  33. }
  34. },
  35. // computed property for form validation state
  36. computed: {
  37. validation: function () {
  38. return {
  39. name: !!this.newUser.name.trim(),
  40. email: emailRE.test(this.newUser.email)
  41. }
  42. },
  43. isValid: function () {
  44. var validation = this.validation
  45. return Object.keys(validation).every(function (key) {
  46. return validation[key]
  47. })
  48. }
  49. },
  50. // methods
  51. methods: {
  52. addUser: function (e) {
  53. e.preventDefault()
  54. if (this.isValid) {
  55. Users.push(this.newUser)
  56. this.newUser.name = ''
  57. this.newUser.email = ''
  58. }
  59. },
  60. removeUser: function (user) {
  61. new Firebase(baseURL + 'users/' + user.id).remove()
  62. }
  63. }
  64. })