Answer the question
In order to leave comments, you need to log in
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')
}
},
},
computed: {
...mapGetters({
items: 'mayModule/getItems',
}),
},
created() {
this.$store.dispatch('mayModule/fetchItems')
},
mounted() {
this.$store.dispatch('mayModule/fetchItems')
}
Answer the question
In order to leave comments, you need to log in
<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>
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 questionAsk a Question
731 491 924 answers to any question