【发布时间】:2022-08-17 00:20:18
【问题描述】:
我正在尝试学习 Vue3 + Pinia,并且我有一个带有异步操作的 Pinia 商店,它可以获取 JSON 数据并将其保存到状态中。在我的 Vue3 模板中,当状态发生变化时(当我们检索到 JSON 数据时),我想运行其他一些函数。我该怎么做呢?
这是我的商店:
import { defineStore } from \"pinia\";
export const useMap = defineStore(\"map-store\", {
state: () => {
return {
locations: [],
fetching: false,
};
},
getters: {
results(state) {
return state.locations;
},
isFetching(state) {
return state.fetching;
},
},
actions: {
async fetchLocations() {
console.log(\"fetching locations\");
this.fetching = true;
const response = await fetch(\"/data/locations.json\");
try {
const result = await response.json();
this.locations = result.locations;
console.log(result.locations);
} catch (err) {
this.locations = [];
console.error(\"Error loading new locations:\", err);
return err;
}
this.fetching = false;
},
},
});
这是我使用该商店的 Vue3 模板:
<script setup>
import { useMap } from \"../store/map.js\";
</script>
<script>
import { mapState, mapActions } from \"pinia\";
export default {
computed: {
...mapState(useMap, { locations: \"results\" }),
},
methods: {
...mapActions(useMap, [\"fetchLocations\"]),
},
created() {
this.fetchLocations();
},
};
</script>
所以我想要做的是,在this.fetchLocations 检索位置并将它们保存为this.locations 之后,我想运行类似addMarkers(){ //add markers to a map based on location data } 的方法。
我该怎么做呢?
标签: javascript vue.js vuex vuejs3 pinia