[英]How to run a function within a vue3 component when state within a Pinia store changes
我正在嘗試學習 Vue3 + Pinia,並且我有一個帶有異步操作的 Pinia 商店,它獲取 JSON 數據並將其保存到 state。 在我的 Vue3 模板中,當 state 發生變化時(當我們檢索到 JSON 數據時)我想運行其他一些 function。 我該怎么做呢?
這是我的商店:
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
保存到 state 之后,我想運行addMarkers(){ //add markers to a map based on location data }
。
我該怎么做呢?
您可以使用watch
選項來觀察 state 更改並在其處理程序中運行您的方法:
watch:{
locations:{
handler(newVal,oldVal){
this.addMarkers();
},
deep:true
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.