Ovaj vodič će vam dati osnovno razumijevanje Vuexa izgradnjom aplikacije za izradu plana. Korisnik može upisati aktivnosti, a zatim glasati koliko im se sviđaju / ne sviđaju.
Nakon što pročitate ovaj vodič, možete pogledati naš besplatni Vuex tečaj o Scrimbi, ako vas zanima više.
Što je Vuex? Iz Vueove službene dokumentacije
Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.
Ovaj tečaj pretpostavlja da ste donekle upoznati s Vueom, a mi ćemo se ukratko dotaknuti značajki poput props
komponenata i veza, ali ih nećemo detaljno pregledavati. Ako želite imati brzi početni tekst o Vueu, slobodno pogledajte ovaj tečaj o Scrimbi.
Postava
U Scrimbi su komplicirane postavke nešto što jednostavno ne radimo.
Za ovaj smo tutorial stvorili jednostavnu HTML datoteku u koju se sve može napisati. Slobodno napišite svoj CSS ili ga jednostavno kopirajte s ovog igrališta
Biblioteke Vue i Vuex uvoze se putem CDN-a pomoću oznaka:
Activity Voter /* ADD CSS HERE */ /* ADD VUE CODE HERE */
Također možete eksperimentirati s kodom na ovom igralištu Vue Scrimba. Samo ne zaboravite ponovo povezati igralište sa svojim računom.
Plan aplikacije
Izgradit ćemo aplikaciju za glasanje, koja posebno dobro funkcionira kada ste u grupi prijatelja koji ne znaju što učiniti, a morate razmotriti sve mogućnosti.
Funkcionalnost će se sastojati od toga da korisnik može upisati aktivnost, a zatim će svaka aktivnost imati gumb za glasanje prema gore i dolje za brojanje ukupnih rezultata.
Početak rada
Prvo, brzo se rugajmo našoj aplikaciji u HTML-u. Koristit ćemo ovaj izgled za izdvajanje u zasebnu komponentu i dodati ćemo funkcionalnost da izgled oživi.
Activity voter
Add Activity
- Go Snowboarding ? ? 5 ?

Dodajte Vuex trgovinu s nekim osnovnim podacima
Vuex započinje s trgovinom. Trgovina je mjesto u kojem čuvamo (čuvamo) svoje stanje.
Vue.use(Vuex); const store = new Vuex.Store({ }); new Vue({ el: "#app", store });
U trgovinu dodamo i neke kodirane podatke koji će sadržavati jednu aktivnost i niz s jednim emoji-em kako bismo prikazali svoje osjećaje prema toj aktivnosti.
Vue.use(Vuex); const store = new Vuex.Store({ state: { activities: [{ name: "go snowboarding", rating: 5 }], emojis: ["?"] } }); new Vue({ el: "#app", store });
Da bismo omogućili da se naše stanje reaktivno mijenja, možemo koristiti Vuex mapState
za obradu izračunatih svojstava stanja za nas.
new Vue({ el: "#app", store, computed: Vuex.mapState(["activities", "emojis"]) });
Dodaj komponentu
Sada imamo aktivnosti unutar naše države. Prikažimo zasebnu komponentu za svaku od tih aktivnosti. Svaki će trebati activity
i emojis
rekvizite.
Vue.component("activity-item", { props: ["activity", "emojis"], template: ` {{ activity.name }} {{ emojis[0] }} ? {{activity.rating}} ? ` });
Inside app
we can now use our newly created component with all the appropriate bindings for activity
and emojis. As a quick reminder, if we want to loop over an array and display a component for each item in an array, in Vue, we can use v-for
binding.
Activity voter
Add Activity

Add mutations to store
If we want to update the store in Vuex, we can use mutations. At the moment we will just console.log
that a mutation happened and we will implement it afterwards.
const store = new Vuex.Store({ state: { activities: [ { name: "go snowboarding", rating: 5 }, ], emojis: ["?"] }, mutations: { increment(state, activityName) { console.log('increment'); }, decrement(state, activityName) { console.log('decrement'); }, } });
How do we trigger a mutation? We call a commit
function on $store
with the name of mutations we want to be executed. Any arguments after the name of a mutation are treated as arguments to a committed mutation.
new Vue({ el: "#app", store, data() { return { activityName: "" }; }, computed: Vuex.mapState(["activities", "emojis"]), methods: { increment(activityName) { this.$store.commit("increment", activityName); }, decrement(activityName) { this.$store.commit("decrement", activityName); } } });
Add functionality to component
Each activity-item
has voting buttons that need to increment
and decrement
on click of a button. We can pass these functions as props. Let's now bind our methods to props.
Let's also not forget to provide activity.name
as an argument to both.
Vue.component("activity-item", { props: ["activity", "emojis", "increment", "decrement"], template: ` {{ activity.name }} {{ emojis[0] }} ? {{activity.rating}} ? ` });
And there we go! The flow is working. We can see the console.log
statement in the console.

Implement counter
Let's implement the counter. First, we need to find an activity by its name, and then update its rating.
mutations: { increment(state, activityName) { state.activities .filter(activity => activity.name === `${activityName}`) .map(activity => activity.rating++); }, decrement(state, activityName) { state.activities .filter(activity => activity.name === `${activityName}`) .map(activity => activity.rating--); } }
Perfect, we can now vote on activities.

Use form input to add activity
But of course, we need to be able to add activities too.
Let's create a mutation to the store, that would add an activity to the list of existing activities, with a name that we will later get from the input and a default rating of 0.
mutations: { ... addActivity(state, name) { state.activities.push({ name, rating: 0 }); } }
Inside methods, we can commit a new activity to the store.
methods: { ... addActivity(activityName) { this.$store.commit("addActivity", activityName); } }
Implement form submission
Let's wire up the submit function to our HTML form.
Add Activity
We can now add our submit function to methods. Inside, we're going to use our existing addActivity
method and in the end, reset activityName
in the input field to an empty string.
methods: { ... onSubmit(e) { e.preventDefault(); this.addActivity(this.activityName); this.activityName = ""; } }
We call e.preventDefault()
to avoid the form from reloading on each addition of a new activity.

All the counters now work and the field gets updated. It does look a bit strange, that we have only one emotion for all the activities, no matter what their rating is.
Let's rewrite emojis into an object with some description of what moods they are meant to reflect and clean up existing state, so we start from no activities.
state: { activities: [], emojis: { yay: "?", nice: "?", meh: "?", argh: "?", hateIt: "?"} }, ...
And as a finishing touch, we can display different emojis depending on the rating an activity has.
Vue.component("activity-item", { props: ["activity", "emojis", "increment", "decrement"], template: `
{{ activity.name }} ` });
We start with a blank app, which is what we wanted.

And now if we add back the two activities we used to have in the app, vote on the ratings we have emojis that reflect how we feel about the activities!

You can check out the full code here.