vue3 组合中的 vuex 模块 axios api
vuex module axios in vue3 composition api
我是 vue 的新手,正在使用 vue 3 和组合 API。很难找到与作文相关的东西API,所以我试着在这里寻求帮助。我将 axios 与 vuex 模块结合使用来消耗 APIs.
如何将此代码从选项 API 转移到组合 API?
TestApi.js
import axios from 'axios'
const posts = {
namespaced: true,
state: {
posts: []
},
mutations: {
SET_POSTS(state, data){
state.posts = data
}
},
actions: {
loadPosts({commit}) {
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then( res => {
commit('SET_POSTS', res.data)
} )
.catch(error => console.log(error))
}
},
getters: {
getPosts(state){
return state.posts
}
}
}
export default posts
App.vue
<template>
<div class="post" v-for="post in getPosts" :key="post.id">
<h1>{{ post.title }}</h1>
<p>{{ post.body }}</p>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
import { computed } from 'vue'
export default {
computed: {
...mapGetters('posts', ['getPosts'])
},
created(){
this.$store.dispatch('posts/loadPosts')
}
}
</script>
<style>
.post{
margin-bottom: 20px;
}
</style>
我试过这样的东西。但它不起作用:
import { useStore } from 'vuex'
import { computed } from 'vue'
export default {
setup(){
getData();
const store = useStore()
function getData(){
store.dispatch('posts/loadPosts');
}
const getPosts = computed(() => store.getters['getPosts'])
return{ getPosts }
}
}
错误:未捕获(承诺)TypeError:无法读取未定义的 属性 'dispatch'
你应该运行初始化商店后的功能:
setup(){
const store = useStore()
getData();
...
我是 vue 的新手,正在使用 vue 3 和组合 API。很难找到与作文相关的东西API,所以我试着在这里寻求帮助。我将 axios 与 vuex 模块结合使用来消耗 APIs.
如何将此代码从选项 API 转移到组合 API?
TestApi.js
import axios from 'axios'
const posts = {
namespaced: true,
state: {
posts: []
},
mutations: {
SET_POSTS(state, data){
state.posts = data
}
},
actions: {
loadPosts({commit}) {
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then( res => {
commit('SET_POSTS', res.data)
} )
.catch(error => console.log(error))
}
},
getters: {
getPosts(state){
return state.posts
}
}
}
export default posts
App.vue
<template>
<div class="post" v-for="post in getPosts" :key="post.id">
<h1>{{ post.title }}</h1>
<p>{{ post.body }}</p>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
import { computed } from 'vue'
export default {
computed: {
...mapGetters('posts', ['getPosts'])
},
created(){
this.$store.dispatch('posts/loadPosts')
}
}
</script>
<style>
.post{
margin-bottom: 20px;
}
</style>
我试过这样的东西。但它不起作用:
import { useStore } from 'vuex'
import { computed } from 'vue'
export default {
setup(){
getData();
const store = useStore()
function getData(){
store.dispatch('posts/loadPosts');
}
const getPosts = computed(() => store.getters['getPosts'])
return{ getPosts }
}
}
错误:未捕获(承诺)TypeError:无法读取未定义的 属性 'dispatch'
你应该运行初始化商店后的功能:
setup(){
const store = useStore()
getData();
...