【问题标题】:How to run a function within a vue3 component when state within a Pinia store changes当 Pinia 商店中的状态发生变化时,如何在 vue3 组件中运行函数
【发布时间】: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


    【解决方案1】:

    您可以使用 watch 选项来观察状态变化并在其处理程序中运行您的方法:

    watch:{
      locations:{
        handler(newVal,oldVal){
           this.addMarkers();
        },
        {
         deep:true
        }
    
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-07
      • 2023-01-24
      • 2022-07-18
      • 2022-07-06
      • 2023-03-06
      • 2022-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多