In Vue.js, you can dispatch Vuex actions to perform asynchronous operations such as API calls, and update the state in the Vuex store. Here is an example of how to dispatch an action in a Vue component:
php<template>
<div>
<ul>
<li v-for="post in posts" :key="post.id">{{ post.title }}</li>
</ul>
</div>
</template>
<script>
import { mapActions } from 'vuex';
export default {
computed: {
...mapActions(['fetchPosts'])
},
data() {
return {
posts: []
};
},
mounted() {
this.fetchPosts()
.then(response => {
this.posts = response.data;
})
.catch(error => {
console.log(error);
});
}
};
</script>
In this example, the mapActions
helper from Vuex is used to map the fetchPosts
action to a computed property in the component. The fetchPosts
action is defined in the Vuex store and makes an API call to fetch posts data.
In the mounted
lifecycle hook, the fetchPosts
action is dispatched using this.fetchPosts()
. When the response is received, the posts
data property is updated with the response data, which is then rendered in the template using a v-for
directive.
Note that you will need to define the fetchPosts
action in your Vuex store before you can use it in your Vue.js application. The fetchPosts
action can be defined as follows:
javascriptactions: {
fetchPosts({ commit }) {
return axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
commit('setPosts', response.data);
return response;
})
.catch(error => {
console.log(error);
throw error;
});
}
},
In this example, the fetchPosts
action makes an API call using Axios and commits a setPosts
mutation to update the posts data in the Vuex store. The fetchPosts
action returns a promise that resolves to the API response.
No comments:
Post a Comment