首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当Pinia存储中的状态发生变化时,如何在vue3组件中运行函数

当Pinia存储中的状态发生变化时,如何在vue3组件中运行函数
EN

Stack Overflow用户
提问于 2022-08-16 16:15:36
回答 1查看 42关注 0票数 1

我正在尝试学习Vue3 + Pinia,我有一个Pinia存储,其中包含一个异步操作,该操作可以获取JSON数据并将其保存到状态。在我的Vue3模板中,当状态发生变化时(当我们检索到JSON数据时),我想运行一些其他函数。我该怎么做?

这是我的店:

代码语言:javascript
复制
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模板:

代码语言:javascript
复制
<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 }的方法。

我该怎么做?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-16 16:20:18

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

代码语言:javascript
复制
watch:{
  locations:{
    handler(newVal,oldVal){
       this.addMarkers();
    },
    deep:true

  }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73377131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档