Simple Vue & Vuex fetch example using @feathersjs for realtime data.
// vuex/store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
messages: []
}
const mutations = {
FETCH_MESSAGES (state, messages) {
state.messages = messages
},
ADD_MESSAGE (state, message) {
state.messages.push(message)
}
}
export default new Vuex.Store({
state,
mutations
})
// vuex/getters.js
export const getMessages = state => state.messages
// vuex/actions.js
import feathers from 'feathers/client'
import socketio from 'feathers-socketio/client'
import io from 'socket.io-client'
const socket = io('http://localhost:3030')
const app = feathers().configure(socketio(socket))
// Get the message service that uses a websocket connection
const messageService = app.service('messages')
export const fetchMessages = function ({dispatch}) {
// Call the messages service on the server via websocket
messageService.find({}).then(result => {
dispatch('FETCH_MESSAGES', result.data)
})
}
export const addMessage = function ({ dispatch }, text) {
messageService.create({ text }).then(result => {
dispatch('ADD_MESSAGE', result)
})
}
// components/Messages.vue<template>
<div>
<input type="text" placeholder="Enter message" v-model="newMessage">
<button type="submit" @click="tryAddMessage">Add message</button>
<ul>
<li v-for="message in messages">
<span>{{ message.text }}</span>
</li>
</ul>
</div>
</template>
<script>
import { getMessages } from '../vuex/getters'
import { fetchMessages, addMessage } from '../vuex/actions'
export default {
data () {
return {
newMessage: ''
}
},
ready () {
this.fetchMessages()
},
methods: {
tryAddMessage () {
var text = this.newMessage
if (text.trim()) {
this.addMessage(text)
}
}
},
vuex: {
getters: {
messages: getMessages
},
actions: {
fetchMessages,
addMessage
}
}
}
</script>
// App.js
<template>
<div id="app">
<Messages></Messages>
</div>
</template>
<script>
import Messages from './components/Messages'
import store from './vuex/store'
export default {
components: { Messages },
store // ES6 equivalent of store: store
}
</script>