Skip to content

Instantly share code, notes, and snippets.

@niallobrien niallobrien/App.vue
Last active Oct 18, 2018

Embed
What would you like to do?
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)
})
}
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.