M
M
Mikhail2021-01-12 20:20:55
Vue.js
Mikhail, 2021-01-12 20:20:55

What is the correct way to get data from a VUE JS component with Vuex?

I see many different examples. Let's say there is a page that displays data received from the api. Works through the Vuex store

Example 1

computed: {
    items: {
      get() {
        return this.$store.getters["mayModule/getItems"];
      },
      set() {
        this.$store.dispatch('mayModule/fetchItems')
      }
    },
  },


Example 2
computed: {
    ...mapGetters({
    items: 'mayModule/getItems',
  }),
},
created() {
    this.$store.dispatch('mayModule/fetchItems')
},


Example 3 same as example 2. Only fetchItems via mounted()

mounted() {
    this.$store.dispatch('mayModule/fetchItems')
  }


+ many more examples. It seems like everything is working. But all the same, what is the subtlety and difference?
How to make such a receipt. When loading the page, we make a request to the API, we receive data, write it to the store, and in the component we receive and render?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Swert, 2021-01-13
@swert-tech

Component

<template>
<p>{{ data }}</p>
</template>

<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'

const store = useStore()

const data = computed(() => store.state.user.data)

store.dispatch('user/get', userId)

</script>


Store

const state = {
    data: []
}

const getters = {}

const actions = {
    async get ({commit}) {
        try {
            // Запрос к апи
            commit('setUser', result)
        } catch (error) {
            throw error
        }
    }
}

const mutations = {
    setUser (state, payload) {
      state.status = 'success'
      state.data = payload
    }
  }
  
  export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question