簡體   English   中英

當 Pinia 商店中的 state 發生更改時,如何在 vue3 組件中運行 function

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM