How to use this data from Vuex inside the component? - vue.js

What is the best way to use this data from the Vuex store's Action in the needed component?
import axios from 'axios'
export default {
namespaced: true,
state: {
items: []
},
actions: {
fetchCategories ({state, commit}) {
return axios.get('/api/v1/categories')
.then(res => {
const categories = res.data
commit('setItems', {resource: 'categories', items: categories}, {root: true})
return state.items
})
}
}
}
Component
export default {
components: {
ThreadCreateModal,
ThreadList
},
data () {
return {
...
}
},
computed: {
...
},
created () {
...
},
methods: {
...
}
</script>
Where and how should I use that action for binding the data in this component?

Use mapState by import it from vuex and call it in computed:
computed: {
...mapState(['items']), // if you dont use namespace
...mapState("your_module_name", ['items'] ) // if you use namespace
},
then you can access it by this.items.
However, you can access it directly this.$store.state.items

Related

On component created hook call Action to fetch data from database and store it in state and then call Getter to get the data

So basically I have this component and I am using its created hook to fetch data using vue-resource and VUEX action, storing that data in store and right after that trying to get that data using VUEX getter but I am unable to do so. Any work around or I am doing something wrong. I am new to Vue!
Component:
import { mapActions } from 'vuex';
import { mapGetters } from 'vuex';
export default {
components: {
categoryHeader: CategoryHeader,
categoryFooter: CategoryFooter,
AddCategory
},
data() {
return {
openCatAdd: false,
categories: [],
pagination: []
}
},
methods: {
...mapActions([
'getCategories'
]),
...mapGetters([
'allCategories'
])
},
created() {
this.getCategories(1);
this.categories = this.allCategories();
// console.log(this.categories);
}
};
Store:
import Vue from "vue";
const state = {
categories: [],
};
const mutations = {
setCategories: (state, payload) => {
state.categories = payload;
}
};
const actions = {
getCategories: ({commit}, payload) => {
Vue.http.get('categories?page='+payload)
.then(response => {
return response.json();
})
.then(data => {
commit('setCategories', data.data);
}, error => {
console.log(error);
})
}
}
const getters = {
allCategories: state => {
console.log(state.categories);
return state.categories;
}
};
export default {
state,
mutations,
actions,
getters
};

Vue dynamic component template not working for promise

<template>
<component :is="myComponent" />
</template>
<script>
export default {
props: {
component: String,
},
data() {
return {
myComponent: '',
};
},
computed: {
loader() {
return () => import(`../components/${this.component}`);
},
},
created() {
this.loader().then(res => {
// components can be defined as a function that returns a promise;
this.myComponent = () => this.loader();
},
},
}
</script>
Reference:
https://medium.com/scrumpy/dynamic-component-templates-with-vue-js-d9236ab183bb
Vue js import components dynamically
Console throw error "this.loader() is not a function" or "this.loader().then" is not a function.
Not sure why you're seeing that error, as loader is clearly defined as a computed prop that returns a function.
However, the created hook seems to call loader() twice (the second call is unnecessary). That could be simplified:
export default {
created() {
// Option 1
this.loader().then(res => this.myComponent = res)
// Option 2
this.myComponent = () => this.loader()
}
}
demo 1
Even simpler would be to rename loader with myComponent, getting rid of the myComponent data property:
export default {
//data() {
// return {
// myComponent: '',
// };
//},
computed: {
//loader() {
myComponent() {
return () => import(`../components/${this.component}`);
},
},
}
demo 2

Accessing constant from a VueJS mixin

I have this component
<script>
const serviceName = 'events'
import { mapState } from 'vuex'
import crud from './mixins/crud'
export default {
mixins: [crud],
data() {
return {
serviceName: serviceName,
apiBaseUri: '/api/v1/' + serviceName,
}
},
computed: {
...mapState({
events: state => state.events.data,
}),
},
mounted() {
this.boot()
},
}
</script>
It defines a serviceName which I need to also use within this crud mixin:
import { mapActions, mapMutations, mapState } from 'vuex'
export default {
data: function() {
return {
loading: {
environment: false,
table: false,
},
}
},
computed: {
...mapState({
form: state => state.events.form,
environment: state => state.environment,
}),
},
methods: {
...mapActions(serviceName, ['load']),
...mapMutations(serviceName, [
'setDataUrl',
'setStoreUrl',
'setErrors',
'setFormData',
'storeFormField',
]),
isLoading() {
return this.loading.environment || this.loading.table
},
boot() {
this.setDataUrl(this.apiBaseUri)
this.setStoreUrl(this.apiBaseUri)
this.load()
},
back() {
this.$router.back()
},
storeModel() {
this.store().then(() => {
this.load()
this.back()
this.clearForm()
})
},
},
}
The problem is that I always get a "serviceName is not defined" error message, since serviceName is used in mapActions() and mapMutations().
The error occurs in
import crud from './mixins/crud'
And it completely ignores things like window.serviceName, which I also tried.
Simplest solution I can think of is move the serviceName definition to another file. For example...
// constants.js
export const SERVICE_NAME = 'events'
then you can import it where required, eg
// in your component, your mixin, etc
import { SERVICE_NAME as serviceName } from './constants'

Vue - Data not computed in time before mount

I'm learning Vue and I've run into a problem where my data returns undefined from a computed method. It seems that the data is not computed by the time the component is mounted, probably due to the get request - wrapping my this.render() in a setTimeout returns the data correctly. Setting a timeout is clearly not sensible so how should I be doing this for best practice?
Home.vue
export default {
created() {
this.$store.dispatch('retrievePost')
},
computed: {
posts() {
return this.$store.getters.getPosts
}
},
methods: {
render() {
console.log(this.comments)
}
},
mounted() {
setTimeout(() => {
this.render()
}, 2000);
},
}
store.js
export const store = new Vuex.Store({
state: {
posts: []
},
getters: {
getPosts (state) {
return state.posts
}
},
mutations: {
retrievePosts (state, comments) {
state.posts = posts
}
},
actions: {
retrievePosts (context) {
axios.defaults.headers.common['Authorization'] = 'Bearer ' + context.state.token
axios.get('/posts')
.then(response => {
context.commit('retrievePosts', response.data)
})
.catch(error => {
console.log(error)
})
}
}
})
It is because axios request is still processing when Vue invokes mounted hook(these actions are independent of each other), so state.posts are undefined as expected.
If you want to do something when posts loaded use watch or better computed if it's possible:
export default {
created() {
this.$store.dispatch('retrievePost')
},
computed: {
posts() {
return this.$store.getters.getPosts
}
},
methods: {
render() {
console.log(this.comments)
}
},
watch: {
posts() { // or comments I dont see comments definition in vue object
this.render();
}
}
}
P.S. And don't use render word as methods name or something because Vue instance has render function and it can be a bit confusing.

How to call a function when store has data

I have to create a video player object but I need the stream object to be present before I create the video player.
The this.stream is populated by vuex data store. but I find the mounted() and created() methods don't wait for store data to be present.
Here is the Player.vue component:
import Clappr from 'clappr';
import { mapActions, mapGetters } from 'vuex';
import * as types from '../store/types';
export default {
name: 'streams',
data() {
return {
player: null
};
},
computed: {
...mapGetters({
stream: types.STREAMS_RESULTS_STREAM
}),
stream() {
return this.$store.stream;
}
},
methods: {
...mapActions({
getStream: types.STREAMS_GET_STREAM
})
},
mounted() {
this.getStream.call(this, {
category: this.$route.params.category,
slug: this.$route.params.slug
})
.then(() => {
this.player = new Clappr.Player({
source: this.stream.url,
parentId: '#player',
poster: this.stream.poster,
autoPlay: true,
persistConfig: false,
mediacontrol: {
seekbar: '#0888A0',
buttons: '#C4D1DD'
}
});
});
}
};
Is there a way to wait for this.stream to be present?
You can subscribe on mutation event, For example if you have a mutation in your store called setStream you should subscribe for this mutation. Here's a code snippet of how to subscribe in mounted method.
mounted: function () {
this.$store.subscribe((mutation) => {
if (mutation.type === 'setStream') {
// Your player implementation should be here.
}
})
}