25.06.2018 Views

Full-Stack Vue.js 2 and Laravel 5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Mutator method<br />

We created the stub for a toggleSaved method in our ListingSave component. This<br />

method should add or remove the listing's ID from the saved state in the store.<br />

Components can access the store as this.$store. More specifically, the saved array<br />

can be accessed at this.$store.state.saved.<br />

resources/assets/components/ListingSave.vue: methods: { toggleSaved() {<br />

console.log(this.$store.state.saved); /* Currently an empty array. [] */ } }<br />

Remember that in the Flux architecture state is read-only. That means we cannot<br />

directly modify saved from a component. Instead, we must create a mutator<br />

method in the store which does the modification for us.<br />

Let's create a mutations property in our store configuration, <strong>and</strong> add a function<br />

property toggleSaved. <strong>Vue</strong>x mutator methods receive two arguments: the store state<br />

<strong>and</strong> a payload. This payload can be anything you want to pass from the<br />

component to the mutator. For the current case, we will send the listing ID.<br />

The logic for toggleSaved is to check if the listing ID is already in the saved array<br />

<strong>and</strong> if so, remove it, or if not, add it.<br />

resources/assets/<strong>js</strong>/store.<strong>js</strong>: export default new <strong>Vue</strong>x.Store({ state: { saved: [] },<br />

mutations: { toggleSaved(state, id) { let index = state.saved.findIndex(saved =><br />

saved === id); if (index === -1) { state.saved.push(id); } else {<br />

state.saved.splice(index, 1); } } } });<br />

We now need to commit this mutation from ListingSave. Commit is Flux jargon<br />

that is synonymous with call or trigger. A commit looks like a custom event<br />

with the first argument being the name of the mutator method <strong>and</strong> the second<br />

being the payload.<br />

resources/assets/components/ListingSave.vue: export default { props: [ 'id' ], methods: {<br />

toggleSaved() { this.$store.commit('toggleSaved', this.id); } } }<br />

The main point of using mutator methods in the store architecture is that state is

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!