Use Vuex to load and add notes.

This commit is contained in:
Lukáš Kucharczyk 2020-09-07 19:58:02 +02:00
parent aba92e2025
commit 6aa5105c48
3 changed files with 35 additions and 7 deletions

View File

@ -19,24 +19,25 @@
</template> </template>
<script> <script>
import { mapState } from 'vuex'
export default { export default {
data() { data() {
return { return {
notes: [
{ id: 0, text: 'This is a note' },
{ id: 1, text: 'And another one.' }
],
current: null, current: null,
content: null content: null
} }
}, },
methods: { methods: {
addNote() { addNote() {
this.notes.push({ id: this.notes.length, text: this.content }) this.$store.commit('ADD_NOTE', {
id: this.notes.length,
text: this.content
})
this.content = '' this.content = ''
} }
}, },
computed: {}, computed: mapState(['notes']),
mounted() { mounted() {
document.addEventListener('keyup', e => { document.addEventListener('keyup', e => {
switch (e.code) { switch (e.code) {

View File

@ -1,4 +1,8 @@
import { createApp } from 'vue' import { createApp } from 'vue'
import App from './App.vue' import App from './App.vue'
import store from './store/index.js'
window.app = createApp(App).mount('#app') window.app = createApp(App)
.use(store)
.use(store)
.mount('#app')

23
src/store/index.js Normal file
View File

@ -0,0 +1,23 @@
import { createStore } from 'vuex'
export default createStore({
state() {
return {
notes: [{ id: 1, text: 'A note from the Vuex store!' }]
}
},
mutations: {
FETCH_NOTES(state) {
state.notes = [
{
id: 1,
text: 'Note loaded via mutation from Vuex!'
}
]
},
ADD_NOTE(state, note) {
state.notes.push(note)
}
},
actions: {}
})