Vuex

Vuex

by WILLIAM CORREA

HTML

<div id="example">
    <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
    <label for="jack">Jack</label>
    <input type="checkbox" id="john" value="John" v-model="checkedNames">
    <label for="john">John</label>
    <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
    <label for="mike">Mike</label>
    <br>
    <span>Checked names: {{ checkedNames }}</span>
</div>
<script src="https://cdn.jsdelivr.net/g/[email protected],[email protected]"></script>

JavaScript

const store = new Vuex.Store({
    state: {
        checkedNames: ['Jack', 'Mike']
    },
    mutations: {
        updateChecked(state, payload) {
            state.checkedNames = payload
        }
    },
    actions: {
        updateChecked({
            commit
        }, payload) {
            commit('updateChecked', payload)
        }
    }
})
new Vue({
    store,
    el: '#example',
    computed: {
        checkedNames: {
            get() {
                return this.$store.state.checkedNames
            },
            set(str) {
                this.$store.dispatch('updateChecked', str)
            }
        }
    }
})