Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Using Vuex for Beginners
- ===================
- 1. Adding Vuex to your package.json
- -----------------------------------------
- ```
- yarn add vuex
- ```
- ```
- npm add vuex
- ```
- 2. Lines of code to add at the App.vue from your Store
- -----------------------------------------
- ```
- new Vuex.store({
- state: { // The data
- products: []
- },
- getters: { // Getting Computed properties
- methodOfGetters() {
- ....
- },
- actions: { // Make calls from an API
- methodOfActions() {
- ....
- }
- },
- mutations: { // Responsable for setting and updating the state
- methodOfMutations() {
- }
- }
- })
- ```
- 3. Using mutations, to update the state, we need to do it with a mutations method to follow the pattern that Vuex offers to us
- -----------------------------------------
- ```
- mutations: { // We need two parameters, the actual state and the payload to be used
- methodOfMutations(state, products) {
- state.products = products
- }
- }
- ```
- 3.1 Then, is followed by the component where you are going to store that data
- ```
- computed: {
- products() {
- return store.state.products
- }
- },
- ```
- 3.2 Finally, to execute the mutation, select the method that you desire to apply it on the component of your choice, to proceed with the mutation, you access the store and commit the mutation, typing the name of the mutation to follow with the payload to update
- ```
- store.commit('methodOfMutations', products)
- ```
- 4. Using the getters to perform simple calculations or retrieve, getters need two parameters, the state and all the actual getters
- -----------------------------------------
- ```
- getters: {
- methodOfGetters(state, getters) {
- return state.products.filter(product => product.inventory > 0)
- }
- },
- ```
- 4.1 Using the getter method in the desired component
- ```
- computed: {
- products() {
- return store.getters.methodOfGetters
- }
- },
- ```
- 5. To perform a better use of actions
- -----------------------------------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement