我正在尝试学习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 }的方法。
我该怎么做?
发布于 2022-08-16 16:20:18
您可以使用watch选项观察状态变化,并在其处理程序中运行您的方法:
watch:{
locations:{
handler(newVal,oldVal){
this.addMarkers();
},
deep:true
}
}https://stackoverflow.com/questions/73377131
复制相似问题