niallobrien
4/14/2016 - 8:47 PM

App.vue

<template>
  <div id="app">
    <img class="logo" src="./assets/logo.png">
    <Hello></Hello>
    <Messages></Messages>
  </div>
</template>

<script>
import Hello from './components/Hello'
import Messages from './components/Messages'

export default {
  components: { Messages, Hello }
}
</script>

<style>
html {
  height: 100%;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

#app {
  margin-top: -100px;
  max-width: 600px;
  font-family: Helvetica, sans-serif;
  text-align: center;
}

.logo {
  width: 100px;
  height: 100px
}
</style>
<template>
  <div>
    <input type="text" placeholder="Enter message" v-model="newMessage" @keyup.enter="tryAddMessage">
    <button type="submit" @click="tryAddMessage">Add message</button>
    <ul>
      <li v-for="message in messages">
        <span>{{ message.text }}</span>
        <span @click="tryRemoveMessage(message)">x</span>
      </li>
    </ul>
  </div>
</template>

<script>
  import * as services from '../services'
  import { getMessages } from '../vuex/getters'
  import { fetchMessages, addMessage, removeMessage } from '../vuex/actions'

  export default {
    vuex: {
      getters: {
        messages: getMessages
      },
      actions: {
        fetchMessages,
        addMessage,
        removeMessage
      }
    },
    data () {
      return {
        newMessage: ''
      }
    },

    ready () {
      this.fetchMessages()
      this.addMessage()
      this.removeMessage()
    },

    methods: {
      tryAddMessage () {
        if (this.newMessage.trim()) {
          // Persist a new message to the db
          services.messageService.create({ text: this.newMessage }).then(this.newMessage = '')
        }
      },
      tryRemoveMessage (message) {
        // Remove message from the db
        services.messageService.remove(message)
      }
    }
  }
</script>
import * as services from '../services'

export const fetchMessages = function ({dispatch}) {
  // Call the messages service on the server via websocket
  services.messageService.find({}).then(messages => {
    dispatch('FETCH_MESSAGES', messages.data)
  })
}

export const addMessage = function ({dispatch}) {
  // A new message has been created on the server, so dispatch a mutation to update our state/view
  services.messageService.on('created', message => {
    dispatch('ADD_MESSAGE', message)
  })
}

export const removeMessage = function ({dispatch}) {
  // A message has been removed from the server, so dispatch a mutation to update our state/view
  services.messageService.on('removed', message => {
    dispatch('REMOVE_MESSAGE', message)
  })
}