Large Application Patterns with Vuex Chapter 18
The HTML layout looks as shown:
<div id="app">
<div v-for="(message, index) in messages">
<p style="cursor:pointer">{{message}}
<span @click="close(index)">[x]</span>
</p>
</div>
<input v-model="newMessage" @keyUp.enter="broadcast">
<button @click="broadcast">Broadcast</button>
</div>
The idea is to have a textbox to write messages and the broadcasted messages will be
displayed on the top with the most recent appearing first. The messages can be dismissed
by clicking on the little x.
First, let's build a store that will hold the list of broadcasted messages and enumerate the
possible mutations we can make to said list:
const store = new Vuex.Store({
state: {
messages: []
},
mutations: {
pushMessage (state, message) {
state.messages.push(message)
},
removeMessage (state, index) {
state.messages.splice(index, 1)
}
}
})
So, we have a list of messages; we can push one to the top of the list or we can remove a
message by knowing its index.
Next, we need to write the logic of the application itself:
new Vue({
store,
el: '#app',
data: {
newMessage: ''
},
computed: Vuex.mapState(['messages']),
methods: {
broadcast () {
store.commit('pushMessage', this.newMessage)